0
我刚刚开始使用React。我试图建立一个多输入字段的表单。加载组件时,这些字段具有默认值。该值是可编辑的。React中具有多个状态值的多个输入
我通过迭代数据来创建字段。一旦编辑了字段,我一直在努力设置状态。这是我迄今为止所掌握的。
var Form = React.createClass({
loadStuff:function(){
console.log(this.props.products);
this.setState({data: this.props.products});
},
onChange: function(opt){
this.setState({data: this.state.data})
},
getInitialState: function(){
return {data: []};
},
componentDidMount: function(){
this.loadStuff();
},
render: function(){
return(
<div>
<InputList data={this.state.data} onChange={this.onChange}/>
</div>
)
}
});
var InputList = React.createClass({
handleChange: function(e){
console.log(' ', e.target.value);
this.setState({value: e.target.value})
},
render:function(){
var boxes = this.props.data.map(function(d){
return(
<input value={d.num} onChange={this.handleChange}/>
)
}.bind(this));
return(
<div>{boxes}</div>
)
}
})
var PRODUCTS = [
{num: 1, name: 'Football'},
{num: 2, name: 'Baseball'},
{num: 3, name: 'Basketball'},
{num: 4, name: 'iPod Touch'},
{num: 5, name: 'iPhone 5'},
{num: 6, name: 'Nexus 7'}
];
ReactDOM.render(<Form products={PRODUCTS}/>,
document.getElementById('content'))
在此先感谢您的帮助。
编辑 - UPDATE
var InputList = React.createClass({
componentWillReceiveProps: function(nextProp){
nextProp.data.map(function(props){
console.log('+++++++', props.num);
this.setState({
value: props.num
})
}.bind(this))
},
handleChange: function(e){
//console.log(' ', e.target.value);
this.setState({value: e.target.value})
},
render:function(){
var boxes = this.props.data.map(function(d){
//console.log(d)
return(
<input value={this.state.value} onChange={this.handleChange}/>
)
}.bind(this));
return(
<div>{boxes}</div>
)
}
})
'this.props.data'总是引用道具你传入,永远不会更新你的状态。你需要'this.state.data'并从道具派生初始状态。请参阅https://facebook.github.io/react/docs/component-specs.html#getinitialstate和https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops。 –
谢谢你指点我正确的方向@Felix。我修改了代码以使用'componentWillReceiveProps'。它只使用所有输入的最后一个值。将不得不进一步调查一下。 – Fred