How to update parent's state in React?

后端 未结 14 1612
粉色の甜心
粉色の甜心 2020-11-22 08:48

My structure looks as follows:

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

Component 3 s

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 09:34

    -We can create ParentComponent and with handleInputChange method to update the ParentComponent state. Import the ChildComponent and we pass two props from parent to child component ie.handleInputChange function and count.

    import React, { Component } from 'react';
    import ChildComponent from './ChildComponent';
    
    class ParentComponent extends Component {
      constructor(props) {
        super(props);
        this.handleInputChange = this.handleInputChange.bind(this);
        this.state = {
          count: '',
        };
      }
    
      handleInputChange(e) {
        const { value, name } = e.target;
        this.setState({ [name]: value });
      }
    
      render() {
        const { count } = this.state;
        return (
          
        );
      }
    }
    
    • Now we create the ChildComponent file and save as ChildComponent.jsx. This component is stateless because the child component doesn't have a state. We use the prop-types library for props type checking.

      import React from 'react';
      import { func, number } from 'prop-types';
      
      const ChildComponent = ({ handleInputChange, count }) => (
        
      );
      
      ChildComponent.propTypes = {
        count: number,
        handleInputChange: func.isRequired,
      };
      
      ChildComponent.defaultProps = {
        count: 0,
      };
      
      export default ChildComponent;
      

提交回复
热议问题