React类,方法绑定(第三部分)
这是React和ECMAScript6/ECMAScript7结合使用系列文章的第三篇。 下面是所有系列文章章节的链接:
你在看上一篇文章中的 如果我们尝试将
这是因为我们当我们调用一个用那种方法绑定的方法时, No autobinding was the decision of React team when they implemented support of ES6 classes for React components. You could find out more about reasons for doing so in this blog post. 当 现在让我们来看看在你的JSX案例中,使用ES6类创建的方法的多种调用方法。我所考虑到的多种不同的方法都在这个GitHub repository。 Method 1. 使用Function.prototype.bind().之前我们已经见到过: export default class CartItem extends React.Component { render() { <button onClick={this.increaseQty.bind(this)} className="button success">+</button> } } 当任何ES6的常规方法在方法原型中进行 Method 2. 在构造函数中定义函数此方法是上一个与类构造函数的用法的混合: export default class CartItem extends React.Component { constructor(props) { super(props); this.increaseQty = this.increaseQty.bind(this); } render() { <button onClick={this.increaseQty} className="button success">+</button> } } 你不要再次在JSX代码的其它地方进行绑定,但是这将增加构造函数中的代码量。 Method 3. 使用箭头函数和构造函数ES6 fat arrow functions preserve this context when they are called. We could use this feature and redefine increaseQty() inside constructor in the following way: 当方法被调用时,ES6 fat arrow functions会保留上下文。我们能使用这个特征用下面的方法在构造函数中重定义 export default class CartItem extends React.Component { constructor(props) { super(props); this._increaseQty = () => this.increaseQty(); } render() { <button onClick={_this.increaseQty} className="button success">+</button> } } Method 4. 使用箭头函数和ES2015+类属性另外,你可以使用ES2015+类属性语法和箭头函数: export default class CartItem extends React.Component { increaseQty = () => this.increaseQty(); render() { <button onClick={this.increaseQty} className="button success">+</button> } } 属性初始化和Method 3中的功能一样。 警告: 类属性还不是当前JavaScript标准的一部分。但是你可以在Babel中自由的使用他们。你可以在这篇文章中了解更多类属性的使用。 Method 5. 使用 ES2015+ 函数绑定语法.最近,Babel介绍了 下面是 export default class CartItem extends React.Component { constructor(props) { super(props); this.increaseQty = ::this.increaseQty; // line above is an equivalent to this.increaseQty = this.increaseQty.bind(this); } render() { <button onClick={this.increaseQty} className="button success">+</button> } } 强调:这个特性是高度的实验,使用它你得自己承担风险。 Method 6. 在调用方法的方使用 ES2015+ 函数绑定语法.You also have a possibility to use ES2015+ function bind syntax directly in your JSX without touching constructor. It will look like: 你也可以直接在非构造函数里面的JSX里面直接使用ES2015+函数绑定。效果如下: export default class CartItem extends React.Component { render() { <button onClick={::this.increaseQty} className="button success">+</button> } } 非常简洁,唯一的缺点是,这个函数将在每个后续渲染组件上重新创建。这不是最佳的。更重要的是,如果你使用像PureRenderMixin的东西将会出现。 结论在这篇文章中,我们已经发现了多种React组建类方法的绑定方法。 参考文档
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |