假设我在下面有这样的布局:
class Navigation extends React.Component {
primaryFun() { console.log('funn') }
secondaryFun() {
this.primaryFun();
}
}
我希望这会调用primary,但我得到一个未定义的,好的。
所以我想我会添加一个构造函数来将函数绑定到:
constructor(props) {
super(props)
this.primaryFun = this.primaryFun.bind(this);
}
但主要乐趣仍未定义。
在我的真实项目中,我在mouseOut事件中调用它们。
像上面这样的感觉应该工作,并且React的文档已经完成,所以在这里找不到多少。
你在寻找这样的东西,在另一个内部调用一个函数
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
您还需要绑定secondaryFun
函数以在其中使用this
。没有它,函数this
内的secondaryFun
将指的是secondaryFun
的函数范围
确保两个函数都具有正确的this
范围。如果您使用的是类属性,请参阅https://babeljs.io/docs/plugins/transform-class-properties/。已经出现在create-react-app使用的babel-preset-react-app上,您可以使用它并将其写为箭头函数,如babel链接所示。并避免必须在构造函数上使用.bind
。
您需要在mouseOut中绑定它
onMouseOut={this.secondaryFun.bind(this)}
或者最佳实践使用Lambda语法。它会为你绑定它
onMouseOut={()=>this.secondaryFun()}