javascript - 如何使用调用位置而不是定义位置的上下文执行方法?

标签 javascript reactjs

我正在尝试创建一个依赖性非常低的组件,并且几乎不需要额外的代码就可以在另一个组件中使用它。我被困在需要设置状态的地方,因为 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/

相关文章:

javascript - .ajaxStart() 和 .ajaxStop() 第一次后未触发

javascript - react : "this" is undefined inside a component function

javascript - Jquery 验证插件的 select 标记顶部的错误放置

javascript - 文件上传对话框触发Show事件

javascript - Angular 7 单例服务 : No provider for Service

javascript - 链接到 Next.js 中的动态路由

reactjs - 如何在 Jest 中模拟 window.alert 方法?

reactjs - 胜利图表背景网格

javascript - react : mount/unmount animation of component with variable height

javascript - 字符串中的第一个字母增加,最后一个字母减少