在React with Redux中如何使双冒号工作

时间:2017-02-06 04:27:44

标签: reactjs redux babel ecmascript-next

我正在尝试在我的React项目中使用ES2017和webpack

我有.babelrc个文件和package.json

这是我的.babelrc文件:

{
  "presets": ["es2017"]
}

这是package.json

 {
  "name": "myapp",
  "version": "1.0.0",
  "private": true,
  "devDependencies": {
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-plugin-syntax-async-functions": "^6.13.0",
    "babel-plugin-syntax-trailing-function-commas": "^6.22.0",
    "babel-plugin-transform-async-to-generator": "^6.22.0",
    "babel-preset-es2017": "^6.22.0",
    "enzyme": "^2.4.1",
    "react-addons-test-utils": "^15.3.0",
    "react-scripts": "^0.4.0",
    "webpack": "^2.2.1"
  },
  "dependencies": {
    "css-loader": "^0.26.1",
    "react": "^15.3.0",
    "react-bootstrap": "^0.30.7",
    "react-dom": "^15.3.0",
    "react-redux": "^4.4.5",
    "react-router": "^3.0.0",
    "react-router-redux": "^4.0.7",
    "redux": "^3.5.2",
    "redux-logger": "^2.6.1",
    "redux-thunk": "^2.1.0",
    "style-loader": "^0.13.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "test": "react-scripts test"
  },
  "eslintConfig": {
    "extends": "./node_modules/react-scripts/config/eslint.js"
  }
}

当我尝试使用双冒号时,控制台报告语法错误

<div onMouseEnter={::this.mouseEnter()}>
</div>

有什么不对吗?

2 个答案:

答案 0 :(得分:2)

为了使用::运算符绑定函数,您需要使用babel-plugin-transform-function-bind插件。

使用以下命令

安装它
npm install --save-dev babel-plugin-transform-function-bind

然后在您的.babelrc中将其包含为

{
    "presets": ["react", "stage-0", "es2015"],
    "plugins": ["transform-function-bind"]
 }

确保使用

安装上述内容
npm install -S babel-preset-stage-0 babel-preset-2015 babel-preset-react

::ES2015+函数绑定语法,而不是ES2017

详细了解 here

答案 1 :(得分:1)

本身不是一个答案,但你可以通过将类方法声明为lambda(或任何其他提到的方法here)来实现类似的行为:

 export class MyComponent extends React.Component {

    mouseEnter = () => {
       console.log('hover');
    }
    render() {
       return <h1 onMouseEnter={this.mouseEnter}>hi!</h1>
    }

 }