Reactjs:带有复选框的setState:选中或未选中

Reactjs: setState with checkbox: checked or unchecked

我目前 "testing the waters" 使用 Reactjs。基于 their docs,我发起了一个我一直坚持的小项目。到目前为止,当复选框被选中时,状态会发生变化,但是......不确定如何更改未选中的状态:

var Foo = React.createClass{(
 getInitialState: function() {
    return {
      location: true,
    }
  },

 onClick: function() {
  this.setState({ location: false });
 },

 render: function() {

    var inlineStyles = {
      display: this.state.location ? 'block' : 'none'
    };
  return (
   <div>
    <input type="checkbox"
     onClick={this.onClick}
    /> show / hide bar
    <hr />
    <div style={inlineStyles}>
     <p>bar</p>
    </div>
   </div>
  );
 }

)};

我需要为我想要的那种东西使用 if statement 吗?未选中时我需要 this.setState.location: true

您需要在单击期间读取复选框的状态,并将其应用到您的 React 状态。

var Foo = React.createClass({
    render: function() {
        return <input type="checkbox" onClick={this.onClick} checked={!this.state.location}></input>
    },
    
    onClick: function(e) {
        this.setState({location: !e.target.checked});
    },
    
    getInitialState: function() {
        return {
            location: true
        };
    }
});