javascript React:根据状态设置禁用属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33673520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:46:55  来源:igfitidea点击:

React: setting the disabled attribute based on a state

javascriptreactjsreact-jsx

提问by jolyonruss

I'd like to set the disabled attribute on a Button based on component's state, something like this:

我想根据组件的状态在 Button 上设置 disabled 属性,如下所示:

render() {
  return (
    <button type="button" {this.state.submitting ? 'disabled' : ''} 
      onClick={ this.handleSubmit }>Submit</button>
    );
}

At the moment I get an Unexpected token error on the opening {, what am I missing?

目前我在开始时收到一个意外的令牌错误 {,我错过了什么?

回答by Alexander T.

You can set disabledproperty through boolean value, like this

您可以disabled通过布尔值设置属性,如下所示

<button
  type="button"
  disabled={this.state.submitting}
  onClick={this.handleSubmit}
>
  Submit
</button>

Example

Example

回答by Ol' Dawg

You could use null

你可以使用 null

<button type='button' disabled={this.state.submitting ? 'disabled' : null} onClick={this.handleSubmit}>Submit</button>

回答by HKG

If you wanted the disabled attr to be added dependant on some condition you can do something like this:

如果您希望根据某些条件添加禁用的属性,您可以执行以下操作:

const disableBtnProps = {};
if (some condition) {
  disableBtnProps.disabled = false;
} else {
 disableBtnProps.disabled = true;
}

Then in your component you could do:

然后在您的组件中,您可以执行以下操作:

 <Button {...disableBtnProps} className="btn"> my button </Button>