简体   繁体   English

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

[英]In React with Redux how to make double colons work

I am trying to use ES2017 in my React project with webpack 我正在尝试在我的React项目中使用ES2017和webpack

I have a .babelrc file, and a package.json . 我有一个.babelrc文件和一个package.json

this is my .babelrc file: 这是我的.babelrc文件:

{
  "presets": ["es2017"]
}

and this is package.json : 这是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"
  }
}

When I am trying to use double colon, console reports syntax error 当我尝试使用双冒号时,控制台报告语法错误

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

anything wrong? 哪里不对了?

In order to make use of the :: operator to bind the function, you need to use the babel-plugin-transform-function-bind plugin. 为了使用::运算符绑定函数,您需要使用babel-plugin-transform-function-bind插件。

Install it using the below command 使用以下命令安装它

npm install --save-dev babel-plugin-transform-function-bind

and then in your .babelrc include it as 然后在你的.babelrc包含它

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

Make sure you install the above using 确保安装上述内容

npm install -S babel-preset-stage-0 babel-preset-2015 babel-preset-react

:: is the ES2015+ function bind syntax and not ES2017 ::ES2015+函数绑定语法,而不是ES2017

Read more about it here : 在这里阅读更多相关信息:

Not an answer per se, but you can achieve similar behavior by declaring class methods as lambdas (or any other method mentioned here ) : 本身不是答案,但您可以通过将类方法声明为lambda(或此处提到的任何其他方法)来实现类似的行为:

 export class MyComponent extends React.Component {

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

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM