【问题标题】:Best way to recieve props from child to parent react component从子接收道具到父反应组件的最佳方式
【发布时间】:2020-08-10 10:11:38
【问题描述】:

我有一个要保存在数据库中的数组。我有一个页面(父组件)和一个表单(子组件),其中我的生日输入是(我保存在数据库中的那个)。 select html 元素位于子组件中,每次更改后我都会获取它们的值。现在我需要将收到的值从选择元素传递回我的父组件,并使用收到的道具更新数组。我将尽我所能重新创建我的代码:

AuthenticationPage.js(父):

import React from 'react';

class AuthenticationPage extends Component {
    constructor(props) {
        super(props);
        this.state({
            setMonth:null
            setDay:null
            setYear:null
        })
    }
    render() {
        return(
           <div>
           <SignupForm // This is where I call my child component
            onChange={(monthValue) => this.setState({ setMonth: monthValue })}
            initialValues={{ 
              dateofbirth: [
                {
                  month: this.state.setMonth, // This one is okey but I can use onChange just to change one state
                  day: this.state.setDay,
                  year: this.state.setYear
                }
              ]
            }}
            />
           </div>
        )
    }
}

export default AuthenticationPage;

SignupForm.js(儿童):

import React from "react";
import SelectSearch from "react-select-search";

const SignupForm = (props) => (
  <FinalForm
    {...props}
    render={(fieldRenderProps) => {
      const { 
      // Here I render props from parent component
      } = fieldRenderProps;

      function monthPicker(monthValue) {
        props.onChange(monthValue);
        // How can I update the state of setDay and setYear states in parent component
      }

      return (
        <Form className={classes} onSubmit={handleSubmit}>
          <SelectSearch
            options={month}
            onChange={(monthValue) => monthPicker(monthValue)} // This is ok, I change setMonth state in parent with this function
          />
          <SelectSearch
            options={day}
            // How to work with this, this is day input
          />
          <SelectSearch
            options={year}
            // How to work with this, this is year input
          />
        </Form>
      );
    }}
  />
);

export default SignupForm;

所以基本上我想在子组件中的选择元素上发生 onChange 之后更新父组件中的状态。我是 React 新手,一整天都搞不清楚,所以任何帮助都意义重大。

【问题讨论】:

    标签: javascript html node.js reactjs


    【解决方案1】:

    孩子应该收到一个“onChange”功能道具。每次更改表单上的值时,都会在子组件内部调用它 (this.props.onChange(newValue))。

    父级应保存将相应更新的值的状态 (&lt;SignupForm ... onChange={(newValue) =&gt; this.setState({ value: newValue })} /&gt;)

    【讨论】:

    • 这很好用,但我如何处理三个选择项?我需要从每个中获取值,并且我只能在 SignupForm 上使用一个 onChange
    • 子组件:this.props.onChange({ [itemType]: itemValue })
    • 父组件:onChange={(newValue) =&gt; this.setState({ value: ...this.state.value, ...newValue })}
    • 请看我的回答,如果你可以在代码中重新创建它,我已经用最新的尝试更新了它,我包含了你的代码,会非常喜欢它。然后我怎样才能将它引用到父母的正确状态?
    • itemtype应该是什么?
    【解决方案2】:

    从父级到子级可以通过 props 传递数据,但是从子级到父级最好的方式是通过函数,我将尝试在下面编写一个示例,我总是使用函数组件进行编码,所以我的语法不会在下面,但我希望你能明白...

    父组件

    class Parent extends React.Component {
    constructor(props) {
            super(props);
            this.state({
                monthValue:null
            })
        }
    
    // this function send as a prop
    const updateMonthValue =(value)=>{
      this.state.monthValue=value
    }
      render() {
        return <Child updateMonthValue={updateMonthValue} />;
      }
    }
    

    子组件

    const Child =(props) => {
      const submitHandler =(value) =>{
        //here you can call the function of parent and the function in the parent will update state of parent
        props.updateMonthValue(value)
      }
      render() {
        return <h1><button onClick={()=>submitHandler("june")} /></h1>;
      }
    }
    

    【讨论】:

    • 感谢朋友的回复!我试过你的代码,但我收到了这个错误:TypeError: props.updateMonthValue is not a function, the error is called in child component
    • 我能够修改您的代码以满足我的需要,非常完美!非常感谢!
    • @Vuk 我很高兴听到这个消息!
    • "this.state.monthValue=value" ----> 不要在反应中执行此操作,您需要为此使用 setstate,如果您这样做,您的渲染函数将不会运行并且您不会看到变化。
    猜你喜欢
    • 2018-06-01
    • 2015-06-15
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2018-06-28
    • 1970-01-01
    • 2019-12-09
    相关资源
    最近更新 更多