最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reactjs: setState with checkbox: checked or unchecked - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Oct 19, 2015 at 7:15 SylarSylar 12.1k27 gold badges103 silver badges179 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 16

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} checked={!this.state.location}></input>
    },
    
    onClick: function(e) {
        this.setState({location: !e.target.checked});
    },
    
    getInitialState: function() {
        return {
            location: true
        };
    }
});
发布评论

评论列表(0)

  1. 暂无评论