<button onClick={this.plus}>plus</button>
bind()
方法建立一個新的函數, 當這個新函數被調用時其this
置爲提供的值」,什麼意思呢,看代碼:
var module = { x: 42, getX: function() { return this.x; } } var unboundGetX = module.getX; console.log(unboundGetX()); // 調用的對象是window,因此裏面的this.x => window.x // expected output: undefined
var boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // 可是bind以後,會將this的值置爲module提供的值 // expected output: 42
因此代碼修改成 this.plus.bind(this)以後,不過執行時的上下文是什麼,函數的內部的this,始終指向組件提供的值。react
<button onClick={this.handleEdit.bind(this, param)}>編輯</button>
<button onClick={(param) => this.handleEdit(param)}>編輯</button>
constructor(props){ super(props); this.handleEdit = this.handleEdit.bind(this); }
const handleEdit = (e) => { console.log(e) }
<button onClick={::this.click}></button
<button v-on:click="say('what')">Say what</button