React: setting the disabled attribute based on a state

丶灬走出姿态 提交于 2019-12-22 02:04:24

问题


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

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?


回答1:


You can set disabled property through boolean value, like this

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

Example




回答2:


You could use null

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



回答3:


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>


来源:https://stackoverflow.com/questions/33673520/react-setting-the-disabled-attribute-based-on-a-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!