尝试找出如何动态处理表单的不同数量的 props 数据。我的谷歌搜索一无所获。我正在根据相关用户拥有的狗的数量收集预约数量的数据。所以 Prop 看起来像这样:
this.props: {
user: {
id: 11
name: "Steve",
age: 32
}
dogs: [{
id: 18,
name: "Rover"
},{
id: 42,
name: "Snugglemittens"
}]
}
每个用户都有不同数量的狗。我的父元素 View 如下所示:
render(){
<form onSubmit={this._handleSubmit.bind(this)}>
{this.props.dogs.map((dogge)=>{
return(<MsgView dog={dogge} key={dogge.id} />;)
}}
<button type="submit">Submit</button>
</form>
}
然后在每个消息 View 中,我想收集关于每只狗的两个复选框:
render(){
<div className="form-group" data-toggle="buttons">
<label><input type="checkbox" autoComplete="off"/> XYZ </label>
</div>
<div className="form-group" data-toggle="buttons">
<label><input type="checkbox" autoComplete="off"/> ABC </label>
</div>
}
我不知道如何使用ajax将填写的数据返回到我的后端。我最初的想法是使用状态来收集信息并立即将其发送回来。我很确定 React 可以通过我可以使用的 prop 传递函数,但我找不到一个好的例子。
最佳答案
这就是我认为可行的方法。您可以在 View 加载时填充 this.state
,
// or in a lifecycle method componentWillMount or componentDidMount instead
// and do in constructor, this.state = { dogs: [] }
// sorry, this is kind of hard to do abstractly
constructor(props) {
super(props)
// on pageload, set initial state to the doggo array
this.state = {
dogs: this.props.dogs
}
}
// alternate solution potential:
componentDidMount() {
this.setState({ dogs: this.props.dogs })
}
_handleSubmit() {
console.log('FIELDS:', this.state.dogs)
// now we're in business if you see your data
}
render(){
if (this.state.dogs.length === 0) return <div>No dogs yet, loading spinner</div>
return (
<form onSubmit={() => this._handleSubmit()}>
{this.state.dogs.map((dogge)=> {
return(
<MsgView
dog={dogge}
key={dogge.id}
{/* on change, update state of field */}
onChange={(e) => this.setState({
{/* ie: dogs[0], dogs[45]
you might have to use ES6 .find() or something
you guys/girls see where I'm going with this
basically update the array or make better data structure.
I like the idea of this.state.dogs[doggo]
(so dogs is an object with dynamic keys)
then you can just update the value of that key with setState */}
dogs[this.state.dogs.indexOf(dogge)]: e.target.value
})}
/>
)}
}
<button type="submit">Submit</button>
</form>
)
}
我不记得它是否是e.target.value
,但你应该明白我的意思。
- 您将狗从 props 转移到组件状态
- 保持状态最新
- 提交后读取
关于javascript - ReactJS 使用 Props 数组改变表单输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46531481/