TLDR:使用defaultChecked而不是检查,这里http://jsbin.com/mecimayawe/1/edit?js,output阵营复选框不发送的onChange
工作jsbin试图安装一个简单的复选框,当它被选中,将划掉其标签文本。出于某种原因,当我使用组件时,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);
解决方案:
使用检查不让潜在价值变动(明显),因此不会调用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>
);
}
});
首先,为什么不添加一个onChange只是 'this.setState({checked:!this.state.checked})' 比存储一个值容易得多。然后在检查的attrubute中有一个三元运算符:'checked = {this.state.checked? 'checked':null}' – zackify 2014-10-28 18:34:23
这就是它的开始,但它似乎没有更新。所以我开始在这里和那里调试,以调试没有被解雇的东西。理想情况下,完成后会回到最简单的形式:) – jdarling 2014-10-28 18:37:15
假设你的mountNode是一个实际的dom节点,你将不得不使用'this.refs.complete.getDOMNode()。checked'。看到小提琴http://jsfiddle.net/d10xyqu1/ – trekforever 2014-10-28 18:42:44