How to parse data from child to parent using react

2019-08-17 04:15发布

问题:

Hi I am currently working on reactjs but in very basic level. I was trying to parse data from parent to child as well as child to parent. Parent to child is working properly but child to parent I couldn't.

Here is the whole scenario... I have 3 components.. App, Home and User. From App component to Home component I want to parse data.. It is working properly. In Home component I have an Input field. If I write something and click on button then the input value will parse into App component. App is my parent and Home is child..

Here is the code... APP Component

    constructor() {
          super() 
          this.state = {
              userName : ' '
          };
      }
    changeUName(newName) {
        this.setState({
            userName: newName
        });
        console.log('user',newName);  // Getting Undefined
    }

  render() {

    return (

      <div className="App">

        <Home changeUser = {() => this.changeUName()} />
      </div>
    );
  }

Child Component User

constructor(props) {

        super();

        this.state = {

            userName: ''

        };
    }
    changeUName(event) {
        this.setState({
            userName: event.target.value
        });
    }

    nameChange() {
        console.log(this.state.userName)         // If I write "Test" in input field. I will get the value here. 

        this.props.changeUser(this.state.userName); // Once I parse this value, I am getting undefined..
    }

    render() {
        return(                              
            <div>
                <h1> HOME Page</h1>
                Name : <input type="text" value={this.state.userName} onChange={(event) => this.changeUName(event)} ref="uName"/><br/>
                <button onClick={() => this.nameChange()}>Click</button>
            </div>
        )
    }

I do not know where it is going wrong. Please guide me. Thanks in advance..

回答1:

The thing is that you are not binding the props recieved to the function definition. See the below snippet

class Parent extends React.Component { 
   constructor() {
          super() 
          this.state = {
              userName : ' '
          };
      }
    changeUName(newName){
        this.setState({
            userName: newName
        });
        console.log('user',newName);  // Getting Undefined
    }

  render() {

    return (

      <div className="App">

        <Home changeUser = {(value) => this.changeUName(value)} />
      </div>
    );
  }
}
class Home extends React.Component {
  constructor(props) {

        super();

        this.state = {

            userName: ''

        };
    }
    changeUName(event) {
        this.setState({
            userName: event.target.value
        });
    }

    nameChange() {
        console.log(this.state.userName)         // If I write "Test" in input field. I will get the value here. 
        
        this.props.changeUser(this.state.userName); 
    }

    render() {
        return(                              
            <div>
                <h1> HOME Page</h1>
                Name : <input type="text" value={this.state.userName} onChange={(event) => this.changeUName(event)} ref="uName"/><br/>
                <button onClick={() => this.nameChange()}>Click</button>
            </div>
        )
    }
    
}

ReactDOM.render(<Parent/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Or else Specify the funtion with arrow function

 changeUName = (newName) =>{
        this.setState({
            userName: newName
        });
        console.log('user',newName);  // Getting Undefined
    }

and call it like

<Home changeUser = {this.changeUName} />


回答2:

The culprit is this line of code:

<Home changeUser = {() => this.changeUName()} />

You call changeUName without any parameter. You should write instead:

<Home changeUser = {name => this.changeUName(name)} />

Or

<Home changeUser = {this.changeUName} />

By the way, have you considered storing your user name into a redux store ? If you haven't studied that yet, you should definitely look into it. In this case you would store the user name in the redux store, and pass it to the App (and other components) by injecting it to their props.