React - 你如何从另一个函数内部调用一个函数

IT技术 javascript reactjs
2021-04-27 01:09:29

假设我在下面有这个布局:

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

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

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

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

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

但主要乐趣仍未定义。

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

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

4个回答

你在寻找这样的东西在另一个内部调用一个函数吗

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;

在这里,当你点击“世界,你好” secondaryFun被称为和内部secondaryFunprimaryFun是被触发

您还需要绑定secondaryFunthis在其中使用函数没有那个,this函数内部将指的secondaryFun是函数作用域,它是secondaryFun

您需要在 mouseOut 中绑定它

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

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

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

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