【问题标题】:React handling Form ComponentsReact 处理表单组件
【发布时间】:2020-10-03 20:05:49
【问题描述】:

好的,我正在尝试在另一个页面中提交两个不同的表单作为独立组件 我只有一个按钮来提交两种表单的数据的组件。 所以我很难在页面组件中拥有一个共享状态,我需要在提交时将每个表单组件的整个状态传递给我的页面组件。 任何人都可以为我的用例推荐最佳实践吗?

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>
    );
  }

【问题讨论】:

  • 我建议在每个字段的模糊中,通过将函数作为道具传递到此组件中,然后在单击提交时提交数据

标签: javascript reactjs forms components react-props


【解决方案1】:

在父组件中定义你的状态并在 props 中传递

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>
    );
  }
}

我还定义了someState,您可以将其作为道具传递给子/表单组件。一旦你在其中使用handleChange 设置状态,它将在父组件中设置状态,你可以使用该状态submitData

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多