如何将数据传递到表单以在ReactJS中进行编辑?
我有3个组件,表格,表单和父组件。
return (
<Table />
<Form />
);
表格呈现项目列表,每行都有一个“编辑”按钮
因此,当单击“编辑”按钮时,它将调用带有项目ID的编辑函数(使用道具从父级传递)。
this.props.edit('iAmTheIdOfTheItem');
编辑功能会将ID设置为父组件状态。
edit = (id) => {
this.setState({ id })
}
所选项目将传递到Form组件。
<Form item={ items.find(item => item.id === this.state.id) } />
这应该以Form组件状态存储当前传递的数据。这样我就可以使用这些数据进行任何更改。
单击更新按钮后,会将状态传递给父组件。
可能的解决方案
由于无法安装Form组件,因此无法使用componentDidMount设置状态。
虽然这可以帮助我使用componentDidMount。但是问题在于Form组件被包装在Modal组件中。因此,当我更新值并清除状态中的id时,关闭动画将不起作用。
我可以将其作为最后的手段,但是对我来说这似乎是一个hack,我不确定是否真的需要它。由于我有5个以上的表格,因此对我来说,将每个表格都添加进去看起来并不好。
有更好的方法吗?有什么建议吗?
您可以使用参考文献此。
引用使用的孩子this.child = React.createRef()
并将其传递给您的子组件,如下所示ref={this.child}
。现在您可以使用该子功能,this.child.current.yourChildsFunction("object or data you want to pass")
然后在该子功能上使用传递的数据来设置表单状态。
这是一个完整的例子。沙盒在这里
class Parent extends Component {
constructor(props) {
super(props);
this.child = React.createRef();
}
onClick = () => {
this.child.current.fillForm("Jackie Chan");
};
render() {
return (
<div>
<button onClick={this.onClick}>Click</button>
<br />
<br />
<Child ref={this.child} />
</div>
);
}
}
class Child extends Component {
constructor(props) {
super(props);
this.state = {
name: ""
};
}
handleChange = ({ target }) => {
this.setState({ [target.name]: target.value });
};
fillForm(passedvalue) {
this.setState({ name: passedvalue });
}
render() {
return (
<form>
<label for="name">Name</label>
<input
id="name"
name="name"
onChange={this.handleChange.bind(this)}
value={this.state.name}
/>
</form>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句