React复选框不发送onChange

TLDR:使用defaultChecked而不是选中,在这里工作jsbin http://jsbin.com/mecimayawe/1/edit?js,output

尝试设置一个简单的复选框,当它被选中将交叉标签文本。由于某种原因,当我使用组件时,handleChange不会被触发。任何人都可以解释我做错了什么?

var CrossoutCheckBox = React.createClass({
  getinitialState: function () {
    return {
        complete: (!!this.props.complete) || false
      };
  },handleChange: function(){
    console.log('handleChange',this.refs.complete.checked); // Never gets logged
    this.setState({
      complete: this.refs.complete.checked
    });
  },render: function(){
    var labelStyle={
      'text-decoration': this.state.complete?'line-through':''
    };
    return (
      <span>
        <label style={labelStyle}>
          <input
            type="checkBox"
            checked={this.state.complete}
            ref="complete"
            onChange={this.handleChange}
          />
          {this.props.text}
        </label>
      </span>
    );
  }
});

用法

React.renderComponent(CrossoutCheckBox({text: "Text Text",complete: false}),mountNode);

解:

使用checked不允许底层值改变(显然),因此不调用onChange处理程序。切换到defaultChecked似乎解决这个问题:

var CrossoutCheckBox = React.createClass({
  getinitialState: function () {
    return {
        complete: (!!this.props.complete) || false
      };
  },handleChange: function(){
    this.setState({
      complete: !this.state.complete
    });
  },render: function(){
    var labelStyle={
      'text-decoration': this.state.complete?'line-through':''
    };
    return (
      <span>
        <label style={labelStyle}>
          <input
            type="checkBox"
            defaultChecked={this.state.complete}
            ref="complete"
            onChange={this.handleChange}
          />
          {this.props.text}
        </label>
      </span>
    );
  }
});
要获得复选框的选中状态,路径将是:
this.refs.complete.state.checked

另一种方法是从事件传递到handleChange方法获取它:

event.target.checked

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...