我正在使用React在页面上安装两个相同的组件,
var SelectBox = React.createClass({
getDefaultProps: function() {
return {
value: []
};
},
getInitialState: function() {
return {checked: this.props.value,count: 1};
},
handleClick: function() {
var opt = this.state.checked;
opt.push({id: this.state.count, name: this.state.count});
this.setState({checked: opt, count: this.state.count + 1});
},
render: function() {
var that = this;
var options = this.state.checked.map(item => <option key={'checked-' + that.props.name + item.id} value={item.id}>{item.name}</option>);
return (
<div>
<select multiple={true}>
{options}
</select>
<button type="button" onClick={this.handleClick}>add</button>
</div>
);
}
});
React.render(
<SelectBox name='one'/>,
document.getElementById('one')
);
React.render(
<SelectBox name='two'/>,
document.getElementById('two')
);
然后单击“一个”的按钮,没关系,但是当我单击“两个”的按钮时,一些“一个”出现在“两个”中,为什么?这让我感到困惑。控制台显示:
Warning: flattenChildren(...): Encountered two children with the same key, `.$checked-two1`. Child keys must be unique; when two children share a key, only the first child will be used.
但是做些改变
var a = [{id: 5, name: 5}];
React.render(
<SelectBox name='one' value={a}/>,
document.getElementById('one')
);
它工作正常。发生了什么?有什么问题还是错误?
哦,我发现了真正的原因,getDefaultProps
一次调用并缓存了,返回的任何复杂对象getDefaultProps()
将在实例之间共享,而不是被复制,因此所有未传递显式值prop的SelectBox组件都将在状态下共享相同的检查数组引用。在这种情况下,我应该写:
getInitialState: function() {
var tmp = this.props.value.concat();
return {checked: tmp, count: 1};
},
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句