我正在尝试关注 no-bind React 使用他们推荐的 ES6 类模式的规则:
class Foo extends React.Component {
constructor() {
super();
this._onClick = this._onClick.bind(this);
}
render() {
return (
<div onClick={this._onClick}>
Hello!
</div>
);
}
_onClick() {
// Do whatever you like, referencing "this" as appropriate
}
}
但是,当我需要将参数传递给 _onClick
时,需要更改什么?
我试过类似的方法:
import {someFunc} from 'some/path';
class Foo extends React.Component {
constructor() {
super();
this._onClick = this._onClick.bind(this, a, b);
}
render() {
const {
prop1,
prop2
} = this.props;
return (
<div onClick={this._onClick(prop1, prop2}>
Hello!
</div>
);
}
_onClick = (a, b) => {
someFunc(a, b);
}
}
但是,这不起作用。需要更改什么?
最佳答案
在构造函数中调用 bind
应该只将 this
作为单个参数传递。
this._onClick = this._onClick.bind(this);
在这里,您正在用具有正确 this
绑定(bind)的新属性覆盖属性 this._onClick
。如果您的函数有两个参数,那么您应该在调用时正常传递它们。
将附加参数传递给 bind
意味着返回的函数已经提供了这些参数 - 在您的尝试中,_onClick
函数将始终具有其前两个参数 undefined
,因为 a
和 b
在构造函数中没有值。
现在您已经将 this
绑定(bind)到您的函数,您可以从那里访问 this.props
,而不必传递参数:
import {someFunc} from 'some/path';
class Foo extends React.Component {
constructor() {
super();
this._onClick = this._onClick.bind(this);
}
render() {
return (
<div onClick={this._onClick}>
Hello!
</div>
);
}
_onClick() {
const {
prop1,
prop2
} = this.props;
someFunc(prop1, prop2);
}
}
关于javascript - 避免 React 中的内联函数 : How to bind functions with arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231678/