【发布时间】:2016-08-03 18:14:21
【问题描述】:
我正在构建带有多个复选框的组件 - 每个复选框对应一个类别。
当我在布尔变量中只有一个复选框时,它可以正常工作(类似于Thinking in React),但是当我将状态放入数组时,我会收到不受控制的表单警告:
react.js:20541 警告:CheckComponent 正在将 >type 复选框的受控输入更改为不受控制。输入元素不应从 >受控切换到不受控(反之亦然)。决定在 >组件的生命周期内使用 >受控或不受控的输入元素。
组件:
handleChange: function(e) {
this.props.onUserInput(
this.refs[e.target.name].checked
);
},
render: function(){
var self = this;
return(
<div>
<ul>
{
categories.map(function(d, i){
return (
<li key = {d}>
<input type="checkbox" checked={self.props.checkedBox[i]} name={d} ref={d} onChange={self.handleChange}/>
<span> {d} </span>
</li>
);
})
}
</ul>
</div>
);
}
父组件:
getInitialState: function(){
return{
checkedBox: [true,true,true,true,true,true,true,true,true,true]
};
},
handleUserInput: function(checkedBox) {
this.setState({
checkedBox: checkedBox
});
},
render: function(){
return(
<div>
<CheckComponent checkedBox={this.state.checkedBox} onUserInput={this.handleUserInput} categories={this.props.categories}/>
<DisplayComponent checkedBox={this.state.checkedBox} data={this.props.data}/>
</div>
);
}
这个数组有问题吗?
【问题讨论】:
-
您是否考虑过使用库来为您处理它? react-checkbox-group 已经负责维护复选框的状态,并且可以用作受控和不受控的组件。
标签: javascript reactjs