我正在尝试在我的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>
有什么不对吗?
答案 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>
}
}