猿问

如何从多个子组件获取表单值?

我有一个很大的 HTML 表单,它在多个组件中有多个字段。


所有这些组件都在一个父组件中。


如何提交表单并从所有子组件获取值?


<form>

  <Col md={6} className="mb-3">

     <SameDay />

  </Col>

  <Col md={6} className="mb-3">

     <International />

  </Col>

  <Col md={6} className="mb-3">

     <OutBondTracking/>

  </Col>

  <Col md={6} className="mb-3">

     <FulfilmentOptions />

  </Col>

  <button

    type="button"

    className="btn btn-primary mr-2"

    onClick={() => this.submitHandler()}

  >

    Submit

  </button>

</form>


一只名叫tom的猫
浏览 230回答 3
3回答

慕侠2389804

您可以在子组件(子组件)中传递一个处理程序函数,该函数在父组件中的任何更改和更新状态时触发,例如:class ParentComponent extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; data: {} . // form data&nbsp; &nbsp; }&nbsp; }&nbsp; onChangeHandlerFn = (data) => {&nbsp; &nbsp; // update the state;&nbsp; &nbsp; this.setState({ data })&nbsp; }&nbsp; submitHandler = () => {&nbsp; &nbsp; // your handler function&nbsp; &nbsp; &nbsp;post your data from the state (data)&nbsp; }&nbsp; &nbsp;render() {&nbsp; &nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp; &nbsp; <form>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Col md={6} className="mb-3">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<SameDay />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Col>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Col md={6} className="mb-3">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <International onChangeHandlerFn={this.onChangeHandlerFn}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Col>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Col md={6} className="mb-3">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <OutBondTracking onChangeHandlerFn={this.onChangeHandlerFn} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Col>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Col md={6} className="mb-3">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <FulfilmentOptions onChangeHandlerFn={this.onChangeHandlerFn} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Col>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="button" className="btn btn-primary mr-2"&nbsp; onClick=&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{this.submitHandler}>Submit</button>&nbsp; &nbsp; &nbsp; &nbsp;</form>&nbsp; &nbsp; &nbsp;);&nbsp; &nbsp;}}处理函数onChangeHandlerFn={this.onChangeHandlerFn},如果子组件有任何变化,应该调用它,它会更新父组件的状态

慕桂英3389331

正如你提到你使用redux,你可以创建一个reducer与states具有象所有字段名称:&nbsp;const formState = {&nbsp; &nbsp; name: null,&nbsp; &nbsp; age: 4,&nbsp; &nbsp; address: null};对于每一个input喜欢textfield, textarea, checkbox附加一个onchange事件,它通过分派动作来改变 formState 的状态。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答