React与ES6(三)
如果你看到前篇里 如果把 这是因为 下面我们就看看ES6写的React组件类如何绑定内部方法。 方法一、使用Function.prototype.bind()class CartItem extends React.Component {
render() {
return (
<p className="large-4 column"> <button onClick={this.increaseQty.bind(this)} className="button success">+</button> <button onClick={this.decreaseQty.bind(this)} className="button alert">-</button> </p> ); } }
ES6的类本质就是Javascript方法,从Function的prototype里继承了 方法二、使用在constructor里定义的方法这是方法一和constructor的混合使用: 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> } }
这个方法就是把 方法三、使用箭头方法和构造函数ES6的胖箭头方法被调用的时候保留了 export default class CartItem extends React.Component {
constructor(props) {
super(props);
// this.state = {
// qty: props.initialQty,
// total: 0
// };
this._increaseQty = () => this.increaseQty();
}
render() {
<button onClick={_this.increaseQty} className="button success">+</button> } }
方法四、使用胖箭头方法和ES2015的class propertyexport default class CartItem extends React.Component {
increaseQty = () => this.increaseQty();
render() {
<button onClick={this.increaseQty} className="button success">+</button> }
因此,类属性非常的简洁。 注意:类属性不是当前Javascript的标准,但是Babel已经支持这个功能(stage 0)。你可以看这里了解更多。 方法五、使用ES2015的方法绑定语法Babel又加入了对一个语法糖的支持 export default class CartItem extends React.Component {
constructor(props) {
super(props);
this.increaseQty = ::this.increaseQty;
}
render() {
<button onClick={this.increaseQty} className="button success">+</button> } }
最后老外介绍的几个方法有点地方差别都不大,有的甚至只是调用的地方从constructor换到了JSX里。所以,有些就略去了,其他的可以看看。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |