事件处理
通常,我们在包含派发事件的元素的组件中处理事件。比如在下面的示例中,我们有一个事件处理函数,我们想要在同一个组件中运行函数或方法:
render() {
return (
<button onClick={ this._handleButtonClick }>
click me
</button>
);
}
_handleButtonClick() {
console.log('Button is clicked');
};
这样使用完全可以,因为 _handleButtonClick
是一个函数,而我们也确实将这个函数传给了 属性。问题是这段代码中并没有保持同一个上下文。所以,如果我们在 _handleButtonClick
函数中使用 this
来获取 Switcher
组件的引用时将会报错。
<button onClick={ this._handleButtonClick.bind(this) }>
click me
</button>
但是,这样做的话 bind
函数会一次又一次地被调用,这是因为 button 可能会渲染多次。一种更好的方式是在组件的构造函数中来创建绑定:
构造函数还是部分执行处理函数的好地方。例如,我们有一个表单,但是不想为每个 input 提供一个单独的处理函数。
class Form extends React.Component {
constructor(props) {
super(props);
this._onNameChanged = this._onFieldChange.bind(this, 'name');
this._onFieldChange.bind(this, 'password');
}
return (
<form>
<input onChange={ this._onNameChanged } />
<input onChange={ this._onPasswordChanged } />
</form>
);
}
_onFieldChange(field, event) {
console.log(`${ field } changed to ${ event.target.value }`);
};