What's the right way to pass form element state to sibling/parent elements?

后端 未结 10 752
情话喂你
情话喂你 2020-11-29 15:04
  • Suppose I have a React class P, which renders two child classes, C1 and C2.
  • C1 contains an input field. I\'ll refer to this input field as Foo.
  • M
10条回答
  •  清酒与你
    2020-11-29 15:27

    The concept of passing data from parent to child and vice versa is explained.

    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    
    // taken refrence from https://gist.github.com/sebkouba/a5ac75153ef8d8827b98
    
    //example to show how to send value between parent and child
    
    //  props is the data which is passed to the child component from the parent component
    
    class Parent extends Component {
      constructor(props) {
        super(props);
    
        this.state = {
          fieldVal: ""
        };
      }
    
      onUpdateParent = val => {
        this.setState({
          fieldVal: val
        });
      };
    
      render() {
        return (
          // To achieve the child-parent communication, we can send a function
          // as a Prop to the child component. This function should do whatever
          // it needs to in the component e.g change the state of some property.
          //we are passing the function onUpdateParent to the child
          

    Parent

    Value in Parent Component State: {this.state.fieldVal}

    ); } } class Child extends Component { constructor(props) { super(props); this.state = { fieldValChild: "" }; } updateValues = e => { console.log(e.target.value); this.props.onUpdate(e.target.value); // onUpdateParent would be passed here and would result // into onUpdateParent(e.target.value) as it will replace this.props.onUpdate //with itself. this.setState({ fieldValChild: e.target.value }); }; render() { return (

    Child

    ); } } class OtherChild extends Component { render() { return (

    OtherChild

    Value in OtherChild Props: {this.props.passedVal}
    the child can directly get the passed value from parent by this.props{" "}
    ); } } ReactDOM.render(, document.getElementById("root"));

提交回复
热议问题