对子组件反应本机传递父方法

时间:2019-02-20 08:28:09

标签: reactjs typescript react-native ecmascript-6

我正在尝试将方法从父组件传递给子组件。我认为我的代码是正确的,但仍然显示错误 undefined不是对象(正在评估'_this2.props.updateData')的错误。我不知道出了什么问题,因为我在互联网上搜索了很多,每个人都将道具传递给孩子。请告诉我我想念的是什么

父母:

class Parent extends React.Component {
  updateData = (data) => {
    console.log(`This data isn't parent data. It's ${data}.`)
    // data should be 'child data' when the
    // Test button in the child component is clicked
  }
  render() {
    return (
      <Child updateData={val => this.updateData(val)} />
    );
  }

孩子:

class Child extends React.Component {
  const passedData = 'child data'
  handleClick = () => {
    this.props.updateData(passedData);
  }
  render() {
    return (
      <button onClick={this.handleClick()}>Test</button>
    );
  }
}

4 个答案:

答案 0 :(得分:1)

`class Child extends React.Component {    
    handleClick = () => {
        const passedData = 'child data'
        this.props.updateData(passedData);
    }
    render() {
        return (
            <button onClick={this.handleClick}>Test</button>
        );
    }
}`

答案 1 :(得分:0)

class Parent extends React.Component { 
updateData = (data) => {
  console.log(`This data isn't parent data. It's ${data}.`)
}
render() {
  return (
    <Child updateData={this.updateData} />
  );
}
}

和子组件:`

class Child extends React.Component {
  const passedData = 'child data'
  handleClick = () => {
    this.props.updateData(passedData);
  }
  render() {
    return (
      <button onClick={this.handleClick}>Test</button>
    );
  }
}

`

答案 2 :(得分:0)

您需要直接传递函数,而不是作为回调函数

class Parent extends React.Component {
  updateData = (data) => {
    console.log(`This data isn't parent data. It's ${data}.`)
    // data should be 'child data' when the
    // Test button in the child component is clicked
  }
  render() {
    return (
      <Child updateData={this.updateData} />
    );
  }

答案 3 :(得分:0)

我认为您需要传递这样的功能。 Check out this solution