简体   繁体   中英

Pass value to parent component in React

essentially I have a form component for users to fill out. When they complete an action: onChange={onChange} it returns a value (child component);

function onChange(value) {
  console.log("This is: ", value);
}

I want to pass the value to a state in the parent component ( so that the from can be processed and form data sent ). How can I do this? My constructor looks something like this (parent component);

constructor(props) {
  super(props);
  this.state = {
    form: {
      name: '',
      age: '',
      value: ''
    }
  };
}

Trying to learn react, please go easy as I'm unsure of how to do this. Would love any feedback! Thanks!

Please read the official documentation start guide carefully and patiently when you are a starter.

In react component, state is the internal state and props is the state passed from outside.

You could only modify the state by setState method.

As for the question you ask, you could define a callback function which call setState in parent component, then pass the callback function as props into the child component.

As Zhili said, you should define a function in your parent component that is passed as prop to the child component. Here's a brief example:

const Child = ({ onSubmit }) => (
  <form onSubmit={onSubmit}>
    { /* your <input/>'s here ... */}
  </form>
);

class Parent extends React.Component {
  state = {
    value: null,
  };

  onChildSubmit = (value) => {
    this.setState({
      value,
    });
  }

  render() {
    return (
      <div class="Something">
        <Child onSubmit={} />
      </div>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM