Reactjs: setState with checkbox: checked or unchecked

拟墨画扇 提交于 2019-12-14 04:17:48

问题


I'm currently "testing the waters" with Reactjs. Based on their docs, I have whipped up a small project that I'm stuck with. So far, when the checkbox is checked, the state changes but....not sure how to change a state unchecked:

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>
  );
 }

)};

Do I need to use an if statement for the sort of thing I want? I need to this.setState.location: true when unchecked.


回答1:


You need to read the state of the checkbox during a click, and apply that to your React state.

var Foo = React.createClass({
    render: function() {
        return <input type="checkbox" onClick={this.onClick} value={!this.state.location}></input>
    },

    onClick: function(e) {
        this.setState({location: !e.target.checked});
    },

    getInitialState: function() {
        return {
            location: true
        };
    }
});


来源:https://stackoverflow.com/questions/33208629/reactjs-setstate-with-checkbox-checked-or-unchecked

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