我有这个结构。
<PlayerFormBox>
- <PlayerForm>
我添加了新的动态表单,我想知道如何获取所有输入值 提交时从 PlayerFormBox 中的表单
<PlayerFormBox>
....
render: function () {
var formFields = [];
for(i = 0; i < this.state.numOfPlayers; i++){
formFields.push(<PlayerForm key={i} />);
}
return (
<div className="playerBox">
<input value="add field" type="button" onClick={this.addField} />
<form id = "form" onSubmit={this.handleSubmit}>
{formFields}
<input type="submit" value="submit" />
</form>
</div>
);
}
<PlayerForm>
var PlayerForm = React.createClass({
render: function () {
return (
<div>
<input key={this.props.index} type="text" name="name">
</div>
);
})
最佳答案
您可能应该使 PlayerForm
组件在值更改时触发事件,并将这些值存储在 PlayerFormBox
的状态中。这样您将在提交时获得所有值。事实上,对于React来说,不直接提交表单是一个很好的做法。最好使用您的输入
字段构建模型
,然后使用请求库通过Ajax处理并提交该模型
,适用于 axios 之类的浏览器。
因此,在PlayerForm
中,使其触发事件:
var PlayerForm = React.createClass({
handleChange: function(event) {
// it's passing the index and the value as parameters
this.props.onChange(this.props.index, event.value);
}
render: function () {
return (
<div>
<input key={this.props.index} onChange={handleChange} type="text" name="name">
</div>
);
})
现在,在 PlayerFormBox
上创建一个 PlayerFormChanged
函数,然后在创建新的 PlayerForm
时将其作为处理程序传递:
for(i = 0; i < this.state.numOfPlayers; i++){
formFields.push(<PlayerForm key={i} onValueChange={onPlayerFormValueChange}/>);
}
现在在 onPlayerFormValueChange
函数中,构建一个模型,如下所示:
onPlayerFormValueChange: function(index, value) {
// now you should set this.state.model[index] = value
// Use the imutability helpers here: https://facebook.github.io/react/docs/update.html
// this will result on a setState that will render everything again accordingly
}
现在,提交后,PlayerForm
的状态就有模型了。
关于javascript - 如何使用 ReactJS 从输入字段获取所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918950/