【问题标题】:React Native Pass Parent Method to Child ComponentReact Native 将父方法传递给子组件
【发布时间】:2019-07-13 21:02:26
【问题描述】:

我正在尝试将方法从我的父组件传递给子组件。我认为我的代码是正确的,但它仍然显示错误 undefined is not an object(evalating '_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>
    );
  }
}

【问题讨论】:

    标签: reactjs typescript react-native ecmascript-6


    【解决方案1】:
    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】:

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

    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】:
      `class Child extends React.Component {    
          handleClick = () => {
              const passedData = 'child data'
              this.props.updateData(passedData);
          }
          render() {
              return (
                  <button onClick={this.handleClick}>Test</button>
              );
          }
      }`
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • 请提供您提到的来源的更多详细信息,因为将来链接可能会停止工作以被删除!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-28
        • 2022-11-10
        • 2021-05-26
        • 2020-04-23
        • 2019-01-18
        • 1970-01-01
        • 2022-07-15
        相关资源
        最近更新 更多