React.js和ES6:任何不绑定构造函数中的函数的原因 [英] React.js and ES6: Any reason not to bind a function in the constructor

查看:186
本文介绍了React.js和ES6:任何不绑定构造函数中的函数的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将React组件更新为ES6并遇到此问题中描述的问题 - 无法访问事件处理程序内的React实例(this) - 即不绑定到组件实例。

I'm in the process of updating a React component to ES6 and suffered the problem described in this question - Unable to access React instance (this) inside event handler - namely not binding to the component instance.

感觉当然有效,但我对答案的另一部分感到困惑:

That made sense and of course worked, but I'm confused about the other part of the answer:


请注意绑定函数会创建一个新的功能。你可以
直接在render中绑定它,这意味着每次组件渲染时都会创建一个新函数
,或者在你的
构造函数中绑定它,它只会触发一次。

Be aware that binding a function creates a new function. You can either bind it directly in render, which means a new function will be created every time the component renders, or bind it in your constructor, which will only fire once.

constructor() {
  this.changeContent = this.changeContent.bind(this);
}

vs

render() {
  return <input onChange={this.changeContent.bind(this)} />;
}


我假设在构造函数是性能等的首选方法,但你知道他们对假设的看法!

I'm assuming that binding in the constructor is the preferred approach for performance etc, but you know what they say about assume!

这两种方法有什么权衡取舍?有没有一个人肯定比另一个好?或者没关系?

What are the trade-offs for these two approaches? Is there ever a situation where one is definitely better than the other? Or does it not matter?

推荐答案

构造函数中绑定的下行:反应热加载器将无法正常工作。

Downside of binding in the constructor: react hot loader won't work.

render()中的绑定下行:性能。

Downside of binding in render(): performance.

最近我'我一直这样做。它比渲染中的绑定稍快,但我愿意将性能换成灵活性和我梦寐以求的HMR。

Recently I've been doing this. It's slightly faster than binding in render, but I'm willing to trade the performance for flexibility and my coveted HMR.

render(){
  return <input onChange={(e) => this.handleChange(e.target.value)}>;
}

它提供了更多的灵活性,例如,更容易过渡到规范输入原子。

It gives a little more flexibility, for example, and easier transition to the canonical Input atom.

render(){
  return <input onChange={(x) => this.handleChange(x)}>;
}

或者在你想要的地方添加参数:

Or adding arguments where you want them:

render(){
  return (
    <ul>
      {this.props.data.map((x, i) => {
        // contrived example
        return (
          <li 
            onMouseMove={(e) => this.handleMove(i, e.pageX, e.pageY)}>
          {x}
          </li>
        );
      }}
    </ul>
  );
}

这篇关于React.js和ES6:任何不绑定构造函数中的函数的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆