我正在使用 React,我看到一种常见的做法是在构造函数中绑定(bind)函数,我也想使用它。不过,我并不完全了解 bind 如何对带参数的函数起作用。例如,我有这样的东西:
class MyClass extends Component {
constructor(props) {
super(props);
this.onListClicked = this.onListClicked.bind(this);
}
onListClicked(id) {
// performs some action
}
render() {
return (
// partially removed for brevity, value of myId comes from a loop
<ListItem onClick={ () => this.onListClicked(myId) } />
);
}
}
现在这适用于我的情况,但我没有利用 bind
完全。如果我更改 ListItem
至 <ListItem onClick={this.onListClicked} />
它没有按预期工作。如果 onListClicked
这会起作用不接受任何参数。但是,在这种情况下,我不知道如何利用绑定(bind)。有什么想法吗?
最佳答案
您的问题与绑定(bind)关系不大,实际上是关于 React 如何处理回调 props。
每个 React 事件监听器函数都会传递一个 React 的 SyntheticEvent
实例。对象作为它的第一个参数。
onClick={this.onListClicked}
将调用 onListClicked
函数并传递一个参数给它:React 提供的 SyntheticEvent
对象。
onClick={this.onListClicked.bind(this)}
与上一个示例相同。 onListClicked.bind()
返回一个包装版本的 onListClicked
及其 context object设置为 this
(在您的情况下是您的 React 组件,因为这就是 this
在您进行绑定(bind)时设置的内容)。这个包装版本的函数仍然只接收一个参数:一个 SyntheticEvent
对象。
onClick={(e) => this.onListClicked(myId)}
将调用匿名 fat-arrow 函数并向其传递一个参数:SyntheticEvent
对象,因为匿名 fat-arrow 函数是回调,所有回调都获得该参数。这个匿名的胖箭头函数忽略了它自己的参数,并使用 myId
的值调用 this.onListClicked
。
onClick={() => this.onListClicked(myId)}
与上一个示例相同,只是我们忽略了 SyntheticEvent
,因为我们不关心它。
onClick={this.onListClicked.bind(this, myId)}
,如 another answer 中所建议, 将包装并调用 onListClicked
函数并传递给它两个参数:第一个是 myId
(因为 bind
正在注入(inject) myId
作为参数并将上下文设置为 this
),第二个是 SyntheticEvent
对象。
因此:根据您在 onListClicked
中具体执行的操作,您可能需要也可能不需要将其绑定(bind)到您的 React 组件(或其他上下文)。您真的需要在特定对象中定义变量和函数吗?然后将回调上下文绑定(bind)到该对象,并根据需要调用 this.foo
或 this.bar
。但是,如果您不需要访问这些类型的东西,就没有必要使用 bind
,因为它就在那里。
关于javascript - 如何在 React 中使用绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46266414/