【问题标题】:What is the vanilla javascript equivalent of Lodash's _.bind?Lodash 的 _.bind 的原版 javascript 等价物是什么?
【发布时间】:2017-09-26 16:24:12
【问题描述】:

我在一个包含以下内容的 React 组件中有一个 onClick 道具:

onClick={_.bind(this.callMe, this, argToPass)}

请记住,这是在使用 React.createClass 的 React 组件中,因此组件函数应该绑定到它的上下文。

不幸的是,当我尝试通过执行以下操作来绑定它时:

onClick={this.callMe(argToPass)}

它打破了我的一项测试。

我不想绑定它,因为它像这样作为道具传递:

onClick={this.callMe(argToPass).bind(this)}

b/c 性能问题。

什么是原版 javascript 等价物:

_.bind(this.callMe, this, argToPass)

这将允许函数正确绑定。

谢谢!

【问题讨论】:

  • 老兄。谁在没有解释的情况下投反对票?这是合法的,在一个出色的团队的生产中,并且是一个真正的问题。
  • 我不想通过:this.callMe(argToPass).bind(this) b/c 的性能问题来绑定它。 -- 你的意思是因为那不正确?因为除非this.callMe() 返回一个函数,否则只会抛出一个错误,但即使它发生了,你仍然会有一个错误。 注意我没有投反对票,我只是在评论。
  • 存在性能问题,我不想使用该符号将函数绑定到该组件的上下文。参考这里:daveceddia.com/avoid-bind-when-passing-props

标签: javascript reactjs lodash bind


【解决方案1】:

JS 等价物是Function#bind:

this.callMe.bind(this, argToPass)

btw - 我建议避免在渲染阶段将函数绑定到 props 中。你可以在Why shouldn't JSX props use arrow functions or bind?了解更多信息

【讨论】:

  • 我不想在onClick中绑定。这和this.callMe(argToPass).bind(this)一样吗?
  • 你要求_.bind()的等价物,Function#bind就是它。 react 中的绑定是一个不同的主题,您应该检查我添加到答案中的链接。
【解决方案2】:
onClick = {() => this.callMe(arrtopass)}

试试这个。它是 es6 语法。

【讨论】:

  • 没有骰子。仍然通过测试,但我感谢您的反馈。
【解决方案3】:
import partial from 'lodash/partial'

// bind using Function.bind
onClick={partial(this.callMe.bind(this), argToPass)}

// when binded in constructor or using arrow function
onClick={partial(this.callMe, argToPass)} 

【讨论】:

  • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多