【问题标题】:React Native - Unable to call method from another componentReact Native - 无法从另一个组件调用方法
【发布时间】:2017-02-08 21:35:30
【问题描述】:

我有两个非常简单的课程。我要做的就是从另一个组件调用一个方法,将文本打印到控制台。当用户单击类 2 中的导航按钮时,它应该调用类 1 中的 _printtest 函数,不幸的是,这没有发生。

第一类

 class drawerControl extends Component {

  constructor(props) {
      super(props);
      this._printtest = this._printtest.bind(this);
  };

  _printtest(){
    console.log("Hello World");
  }

  render() {
    return (
        <Home 
            openControlPanel={this.openControlPanel.bind(this)}
            functest={this._printtest}>
        </Home>
    );
  } 
}

第二类

class Home extends Component {

   constructor(props){
    super(props);
    this.callPrint = this.callPrint.bind(this);
    }
    callPrint(){
        this.props.functest()
    }

    render() {
        return (
          <TouchableHighlight onPress={this.callPrint} style=  {styles.button}>
              <Text>Navigate</Text>
          </TouchableHighlight>
        );
      } 

}

要么我得到一个错误,说“this.props.functest”不是一个函数,要么什么都没有发生。这看起来应该非常简单。我该怎么做才能解决这个问题?

【问题讨论】:

    标签: javascript ios reactjs mobile react-native


    【解决方案1】:

    我将您的代码粘贴到一个新的 react-native 项目中,并在我的 Android 手机上对其进行了测试。

    1. 您需要将 CamelCase 用于自定义组件,afaik:DrawerControl
    2. 缺少DrawerControlopenControlPanel() {}
    3. 主要问题:调用console.log() 会打印到iOS 控制台。您需要在终端中运行react-native log-ios 才能查看输出,否则它会显示为好像什么也没发生。

    您提到的关于 this.props.functest 不是函数的错误可能以多种方式发生,但您在此处发布的代码不应该发生这种情况,前提是您进行了我列出的更改。

    【讨论】:

    • 感谢您的回复!我进行了您建议的更改,但每次单击按钮时 ios-log 都会打印“断言失败:15G31 13E230:断言 + 15801 ...”。此外,openControlPanel() 存在于我的实际代码中,我只是没有使用它。
    • 我只在进行此调用时收到该错误:this.props.functest,否则,如果我进行此调用:this.props.functest(),我仍然会收到“不是函数”错误.虽然如果我把函数放在我的 index.ios.js 文件中,它会出于某种原因工作。
    • 试试这个:&lt;TouchableHighlight onPress={this.props.functest} ...
    【解决方案2】:

    我认为问题在于您的props 已经是一个函数。所以你不需要像this.props.functest() 这样称呼它。只需简单地调用

    <TouchableHighlight onPress={this.props.functest}}>
        <Text>Navigate</Text>
    </TouchableHighlight>
    

    我尝试根据您的代码通过 RNPlay 制作一个简单的应用程序,它可以工作。 https://rnplay.org/apps/2LJnbg

    【讨论】:

      【解决方案3】:

      在您的第 1 类更改中。

      <Home 
        openControlPanel={this.openControlPanel.bind(this)}
        functest={this._printtest()}>
      </Home>
      

      你需要调用_printtest函数

      【讨论】:

        【解决方案4】:

        如果您不设置props,您将无法使用它。 props 只是构造函数的一个参数,而不是您实例的属性,这意味着 this.props 未定义。但是,您可以在构造函数中设置 this.props = props

        【讨论】:

        • 感谢您的回复,不幸的是,即使在构造函数中设置道具时,我仍然收到相同的错误。
        • 这不是真的; props 由 React 设置。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-13
        • 2021-10-15
        • 1970-01-01
        • 2022-08-20
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多