1、事件处理
import React, { Component } from 'react';
import { render } from 'react-dom';
class LikeButton extends Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
handleClick(e) {
this.setState({ liked: !this.state.liked });
}
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick.bind(this)}>
You {text} this. Click to toggle.
p>
);
}
}
render(
<LikeButton />,
document.getElementById('example')
);
复制代码
可以看到 React 里面绑定事件的方式和在 HTML 中绑定事件类似,使用驼峰式命名指定要绑定的 onClick 属性为组件定义的一个方法 {this.handleClick.bind(this)}。
注意要显式调用 bind(this) 将事件函数上下文绑定要组件实例上,这也是 React 推崇的原则:没有黑科技,尽量使用显式的容易理解的 JavaScript 代码。
“合成事件”会以事件委托(event delegation)的方式绑定到组件最上层,并且在组件卸载(unmount)的时候自动销毁绑定的事件。
Warning:
如果不在组件销毁的时候解除事件的话,会造成内存泄露的问题。
怎么解决这个问题?这里可以看我的相关文章 react 内存泄露常见问题解决方案
所有通过 JSX 这种方式绑定的事件都是绑定到“合成事件”,除非你有特别的理由,建议总是用 React 的方式处理事件。
通常如果不是直接调用,应该为方法绑定this。绑定方式有以下几种:
class Button extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
button>
);
}
}
复制代码
class Button extends React.Component {
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>
Click me
button>
);
}
}
复制代码
class Button extends React.Component {
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={()=>this.handleClick()}>
Click me
button>
);
}
}
复制代码
class Button extends React.Component {
handleClick=()=>{
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
button>
);
}
}
复制代码
的时候也需要在构造函数中绑定 this,代码量多。
render: function() {
return <p onClick={this.handleClick.bind(this, 'extra param')}>;
},
handleClick: function(param, event) {
// handle click
}
复制代码
方式1
是官方推荐的绑定方式,也是性能最好的方式。方式2和方式3
会有性能影响并且当方法作为属性传递给子组件的时候会引起重渲问题。方式4
是性能比较好的,现在 babel 已经很成熟了,推荐大家使用