Skip to content

Instantly share code, notes, and snippets.

@jerrybendy
Last active August 17, 2016 10:16
Show Gist options
  • Save jerrybendy/da04c6dcc1806860f4ef7362d69d1a31 to your computer and use it in GitHub Desktop.
Save jerrybendy/da04c6dcc1806860f4ef7362d69d1a31 to your computer and use it in GitHub Desktop.
React 组件中调用方法避免使用 .bind(this) 的一种方式,使用 ES6 和 ES7 的新特性
{
"presets": [
"react",
"es2015"
],
"plugins": [
"transform-class-properties"
]
}
import React from "react";
class Button extends React.Component {
/**
* 同时使用 ES7 的类属性语法和 ES6 的箭头语法
* 解决ES6 调用时需要 .bind(this) 的问题
*
* 使用 babel 需要安装 babel-plugin-transform-class-properties, 并配置 .babelrc
*/
onClickHandler = () => {
this.setState({
clicked: true,
});
};
render () {
// 这里直接使用 this.xxx 调用方法
return <button onClick={ this.onClickHandler }>This is button</button>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment