React - Can A Child Component Send Value Back To Parent Form

前端 未结 3 1601
悲&欢浪女
悲&欢浪女 2020-12-23 11:52

The InputField & Button are custom components that go into a form to create a form. My issue is how do I send the data back up to form so that

3条回答
  •  旧巷少年郎
    2020-12-23 12:36

    React's one-way data-binding model means that child components cannot send back values to parent components unless explicitly allowed to do so. The React way of doing this is to pass down a callback to the child component (see Facebook's "Forms" guide).

    class Parent extends Component {
      constructor() {
        this.state = {
          value: ''
        };
      }
    
      //...
    
      handleChangeValue = e => this.setState({value: e.target.value});
    
      //...
    
      render() {
        return (
          
        );
      }
    }
    
    class Child extends Component {
      //...
    
      render() {
        return (
          
        );
      }
    }
    

    Take note that the parent component handles the state, while the child component only handles displaying. Facebook's "Lifting State Up" guide is a good resource for learning how to do this.

    This way, all data lives within the parent component (in state), and child components are only given a way to update that data (callbacks passed down as props). Now your problem is resolved: your parent component has access to all the data it needs (since the data is stored in state), but your child components are in charge of binding the data to their own individual elements, such as tags.

提交回复
热议问题