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