【问题标题】:React - How do you call a function from inside another functionReact - 你如何从另一个函数内部调用一个函数
【发布时间】:2018-03-18 16:25:54
【问题描述】:

假设我的布局如下:

class Navigation extends React.Component {
 primaryFun() { console.log('funn') }

 secondaryFun() {
  this.primaryFun();
 }
}

我本以为这会调用主要的,但我得到一个未定义的,好的。

所以我想我应该添加一个构造函数来将函数绑定到这个:

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

但主要乐趣仍未定义。

在我的实际项目中,我在 mouseOut 事件中调用这些。

感觉上面的内容应该可以工作,而且 React 的文档到处都是,所以在这里找不到太多。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您是否正在寻找这样的东西,在另一个函数中调用一个函数

    import React, { Component } from 'react';
    import './App.css'
    
    class App extends Component {
      constructor(){
        super()
        this.mouseClick = this.mouseClick.bind(this);
        this.primaryFun = this.primaryFun.bind(this);
        this.secondaryFun = this.secondaryFun.bind(this);
      }
    
      primaryFun(){
        console.log('primaryFun funn') 
      }
    
      secondaryFun(){
        console.log('secondaryFun funn') 
        this.primaryFun()
      }
    
      mouseClick(){
        this.secondaryFun()
      }
    
      render() {
        return (
          <div onClick={this.mouseClick}>   
          Hello World!
          </div>
        );
      }
    }
    export default App;

    在这里,当您点击“Hello world”时,会调用 secondaryFun 并在 secondaryFun 内部触发 primaryFun

    【讨论】:

    • 是的,这就是我所说的那种乐趣
    【解决方案2】:

    您还需要绑定secondaryFun 函数以在其中使用this。否则,函数secondaryFun 中的this 将引用secondaryFun 的函数范围

    【讨论】:

      【解决方案3】:

      你需要在你的 mouseOut 中绑定这个

      onMouseOut={this.secondaryFun.bind(this)}
      

      或者作为最佳实践使用 Lambda 语法。它会为你绑定这个

      onMouseOut={()=>this.secondaryFun()}
      

      【讨论】:

        【解决方案4】:

        确保这两个函数都具有正确的this 范围。如果您使用类属性,请参阅https://babeljs.io/docs/plugins/transform-class-properties/。它已经存在于 create-react-app 使用的 babel-preset-react-app 上,您可以使用它并将它们编写为箭头函数,如 babel 链接所示。并且避免在构造函数上使用.bind

        【讨论】:

          【解决方案5】:

          你必须 bind() 两个函数。 你应该这样做:

          class Navigation extends React.Component {
          
              constructor(props) {
                  super(props)
                  this.primaryFun = this.primaryFun.bind(this);
                  this.secondaryFun = this.secondaryFun.bind(this);
              }
          
              primaryFun() {
                  console.log('funn')
              }
          
              secondaryFun() {
                  this.primaryFun();
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2011-05-30
            • 1970-01-01
            • 2021-11-20
            • 1970-01-01
            • 2017-07-11
            • 1970-01-01
            • 2016-01-04
            • 2015-07-04
            • 2014-01-01
            相关资源
            最近更新 更多