问题
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