如何在ReactJS中将数据从子组件发送到父组件

时间:2019-04-25 08:07:32

标签: reactjs

父母伴侣:

    import React, { Component } from 'react';
    import AllNeedStates from 'components/AllNeedStates/AllNeedStates.jsx'

    class Home extends Component {
    constructor(props){
        super(props)
        this.state = {
        needstate: 
        }
    }


    getNeedstate = (need) => {
        this.setState({
            needstate:need
        })
    }

    render() {
        return (
            <div>
                <AllNeedStates onNeedStateChange={this.getNeedstate} />
                {
                    this.state.needstate ?
                    (
                        <p>null</p>
                    ):
                    (
                        <p>{ this.state.needstate }</p>
                    )
                }
            </div>
        );
    }

    }

    export default Home;

子组件:

import React.Component from 'react'

class Child extends Components {

    myFunc = () => {
        this.props.onNeedStateChange('data');
    }


    render(){
        return (
            <div>
                <button onClick={this.myFunc}>submit</button> 
            </div>
        )
    }
}

在这里,我尝试将一些数据从react子组件发送到我的父组件。 但是我遇到了错误。

TypeError: this.props.onNeedStateChange is not a function

请看看。

当我单击子组件上的按钮时,我需要更改父状态。

2 个答案:

答案 0 :(得分:1)

(1)通过默认值初始化状态,
(2)在render()中显示时检查是否为空

//Parent Component 
import React, { Component } from "react";
import AllNeedStates from "./Child";

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      needstate: ""
    };
  }

  getNeedstate = need => {
    console.log(need);
    this.setState({
      needstate: need
    });
  };

  render() {
    return (
      <div>
        <AllNeedStates onNeedStateChange={this.getNeedstate} />
        {this.state.needstate === null ? (
          <p>null</p>
        ) : (
          <p>{this.state.needstate}</p>
        )}
      </div>
    );
  }
}

export default Home;

答案 1 :(得分:0)

还必须在子组件中添加constructor,否则它将不会从父组件继承props

class Child extends Component {

    constructor(props){
       super(props)
    }

    myFunc = () => {
        this.props.onNeedStateChange('data');
    }


    render(){
        return (
            <div>
                <button onClick={this.myFunc}>submit</button> 
            </div>
        )
    }
}