Disable does not work for checkbox when using this.props

天大地大妈咪最大 提交于 2019-12-11 00:58:57

问题


How do I make this work?

<input type="checkbox" id={"delivery-" + this.props.ID} {this.props.disableIt ? 'disabled' : ''} />

I was expecting this code - {this.props.disableIt ? 'disabled' : ''} - to output a 'disabled' attribute, but it throws 'Unexpected token (102:89)'. But if I directly just put a static 'disabled' word in there, it works.


回答1:


When using react, disabled it's a prop that you need to set true or false. When you just define the prop without a value, and this prop it's boolean, then by default sets the value to true. That's why it works when you manually define the prop.

<input type="checkbox" disabled={false} />
<input type="checkbox" disabled={true} />
<input type="checkbox" disabled />
<input type="checkbox" id={"delivery-" + this.props.ID} disabled={this.props.disableIt} />

For example:

var Example = React.createClass({
  getInitialState: function() {
    return {
      disabled: false
    };
  },

  toggle: function() {
    this.setState({
      disabled: !this.state.disabled
    });
  },

  render: function() {
    return (
      <div>
        <p>Click the button to enable/disable the checkbox!</p>
        <p><input type="button" value="Enable/Disable" onClick={this.toggle} /></p>
        <label>
          <input type="checkbox" disabled={this.state.disabled} />
          I like bananas!
        </label>
      </div>
    );
  }
});

ReactDOM.render(
  <Example />,
  document.getElementById('container')
);

Here's the working example: https://jsfiddle.net/crysfel/69z2wepo/59502/

Good luck!



来源:https://stackoverflow.com/questions/39990002/disable-does-not-work-for-checkbox-when-using-this-props

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