我正在尝试创建一个依赖性非常低的组件,并且几乎不需要额外的代码就可以在另一个组件中使用它。我被困在需要设置状态的地方,因为 setState
方法需要 this
上下文。
目前我正在发送 this
,作为我的库组件中定义的方法的上下文。
export const showSnackbarNotification = (context, msg, variant) => {
context.setState({
[`notificationMsg`]: msg,
[`notificationToggle`]: true,
[`variant`]: variant
})
}
我像下面这样调用这个函数:
showSnackbarNotification(this, "checking the function", "error");
但我不希望用户通过方法参数发送 this
上下文。有什么方法可以让我在调用方法的上下文中执行该方法。所以 showSnackbarNotification
定义变成:
export const showSnackbarNotification = (msg, variant) => {
this.setState({
[`notificationMsg`]: msg,
[`notificationToggle`]: true,
[`variant`]: variant
})
}
并且仍然设置我调用 showSnackbarNotification
方法的组件的状态。
最佳答案
使用常规函数:
export function showSnackbarNotification(msg, variant) {
this.setState({
[`notificationMsg`]: msg,
[`notificationToggle`]: true,
[`variant`]: variant
})
}
当你调用它时,你可以使用 .call
设置上下文:
showSnackbarNotification.call(this, "checking the function", "error");
箭头函数始终具有声明它们的上下文。常规函数采用调用它们的上下文。
Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?
关于javascript - 如何使用调用位置而不是定义位置的上下文执行方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764236/