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)}。javascript
注意要显式调用 bind(this) 将事件函数上下文绑定要组件实例上,这也是 React 推崇的原则:没有黑科技,尽可能使用显式的容易理解的 JavaScript 代码。html
React 实现了一个“合成事件”层(synthetic event system),这个事件模型保证了和 W3C 标准保持一致,因此不用担忧有什么诡异的用法,而且这个事件层消除了 IE 与 W3C 标准实现之间的兼容问题。java
“合成事件”还提供了额外的好处:react
“合成事件”会以事件委托(event delegation)的方式绑定到组件最上层,而且在组件卸载(unmount)的时候自动销毁绑定的事件。浏览器
好比你在 componentDidMount 方法里面经过 addEventListener 绑定的事件就是浏览器原生事件。babel
使用原生事件的时候注意在 componentWillUnmount 解除绑定 removeEventListener。dom
Warning: 若是不在组件销毁的时候解除事件的话,会形成内存泄露的问题。 函数
怎么解决这个问题?这里能够看个人相关文章 react 内存泄露常见问题解决方案post
全部经过 JSX 这种方式绑定的事件都是绑定到“合成事件”,除非你有特别的理由,建议老是用 React 的方式处理事件。性能
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>
);
}
}
复制代码
render: function() {
return <p onClick={this.handleClick.bind(this, 'extra param')}>; }, handleClick: function(param, event) { // handle click } 复制代码
方式1
是官方推荐的绑定方式,也是性能最好的方式。方式2和方式3
会有性能影响而且当方法做为属性传递给子组件的时候会引发重渲问题。方式4
是性能比较好的,如今 babel 已经很成熟了,推荐你们使用