core-decorators的@autobind在React中无效

首先,babel的环境是没有问题的,因为我自己写的decorator是有效的。

代码

import {autobind} from 'core-decorators';
...
<div className="tc common-op"
     onClick={this.handleShow}>
        <i className="icon iconfont">&#xe603;</i>
</div>,
...
@autobind
  handleShow(){
    console.warn(this);
    this.props.handleTableCustomizeShow(true);
  }

结果

图片描述

也就是说,this为依然为null,难道是我的想法不对?@autobind并不能解决React里事件中this的bind问题?

补充

core-decorators.jsGitHub首页的@autobind发现了note:

Note: there is a bug in react-hot-loader <= 1.3.0 (they fixed in 2.0.0-alpha-4) which prevents this from working as expected. Follow it here

但是我将react-hot-loader升级到1.3.1依然无效,看来可能是react-hot-loader导致的,没办法,只好先暂停core-decorators.js的使用,后面再引入吧。

对此各位有其他的解决方案吗?

阅读 6.2k
2 个回答

they fixed in 2.0.0-alpha-4

不知道是不是这个?

添加安装这个 transform-class-properties,(或者react提供的create-react-app,默认已经包含了)

npm install --save-dev babel-plugin-transform-class-properties
# 还有在 babelrc 或者配置中添加
"plugins": ["transform-class-properties"]

写法就变成

class SayHello extends React.Component {
  handleClick = () => {
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题