[英]React handling Form Components
Alright I am trying to submit two different forms as independent components in another page component where I only have one button to submit the data of both forms.好吧,我正在尝试将两个不同的 forms 作为独立组件提交到另一个页面组件中,我只有一个按钮来提交两个 forms 的数据。 So I am struggling to have a shared state in the page component and I need to pass the whole state of each form component to my page component on submit.
因此,我正在努力在页面组件中共享 state,我需要在提交时将每个表单组件的整个 state 传递给我的页面组件。 Can anyone recommend a best practice for my use case?
任何人都可以为我的用例推荐最佳实践吗?
render() {
return (
<div as={Row} className="container" style={formStyle}>
<Col>
<Form onSubmit={this.submitData}>
<TripForm />
<PostForm heading="add your first blog entry" />
<Button variant="dark" type="submit">
Summing up
</Button>
</Form>
</Col>
</div>
);
}
define your state in the parent component and pass it down in props在父组件中定义您的 state 并将其传递给道具
class PageComponent = {
state = { } //define your state here
handleChange = () => {} // define a function that handles changing state
submitData = () => {
// in here you can access this.state and then submit form data with that state
}
render() {
return (
<div as={Row} className="container" style={formStyle}>
<Col>
<Form onSubmit={this.submitData}>
<TripForm handleChange={handleChange} someState={someState} />
<PostForm heading="add your first blog entry" handleChange={handleChange} someState={someState}/>
<Button variant="dark" type="submit">
Summing up
</Button>
</Form>
</Col>
</div>
);
}
}
I've also defined someState
which you can pass down as props to the child/form components.我还定义
someState
,您可以将其作为道具传递给子/表单组件。 once you set state in there with handleChange
it will set state in the parent component and you can submitData
with that state一旦你用 handleChange 在其中设置
handleChange
,它将在父组件中设置 state ,你可以使用submitData
提交数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.