2017-12-02 286 views
2

我遇到了一個我無法解釋的語法錯誤。我對jsx相當陌生並且有反應,所以請和我一起裸照。無法解釋的語法錯誤。 React,JSX

代碼:

import React, { Component } from 'react'; 

class Button extends Component{ 
    handleClick =() => { 
    this.props.onClickFunction(this.props.incrementValue) 
    } 

    render() { 
    return (
     <button onClick={this.handleClick}> 
     +{this.props.incrementValue} 
     </button> 
    ); 
    } 
} 

錯誤信息 - 意外的令牌(4:14):

2 | 
    3 | class Button extends Component{ 
> 4 | handleClick =() => { 
    |    ^
    5 |  this.props.onClickFunction(this.props.incrementValue) 
    6 | } 
    7 | 

我有這個代碼之前的工作,但我想用的WebPack和因爲這些變化進行實驗,我收到此錯誤。據我瞭解,這是es2015中引入的新語法。我相信我擁有了一切正確配置:

"devDependencies": { 
    "axios": "^0.17.1", 
    "babel-cli": "^6.26.0", 
    "babel-core": "^6.26.0", 
    "babel-loader": "^7.1.2", 
    "babel-preset-es2015": "^6.24.1", 
    "babel-preset-react": "^6.24.1", 
    "bootstrap": "^4.0.0-beta.2", 
    "font-awesome": "^4.7.0", 
    "react": "^16.2.0", 
    "react-dom": "^16.2.0", 
    "react-fontawesome": "^1.6.1", 
    "react-scripts": "1.0.17", 
    "reactstrap": "^5.0.0-alpha.4", 
    "webpack": "~3.9.1", 
    "webpack-dev-server": "^2.9.5" 
    } 

module.exports = { 
    entry: "./index.js", 
    output:{ 
     filename:"public/bundle.js" 
    }, 
    module:{ 
     loaders:[ 
      { 
       test: /\.jsx?$/, 
       exclude: /(node_modules|bower_components)/, 
       loader: 'babel-loader', 
       query:{ 
        presets:['react', 'es2015'] 
       } 
      } 
     ] 
    } 
} 

我的第一個念頭是,也許我的ES2015配置不正確。不過,我嘗試使用正常功能語法和仍收到以下錯誤:

2 | 
    3 | class Button extends Component{ 
> 4 | handleClick = function(){ 
    |    ^
    5 |  this.props.onClickFunction(this.props.incrementValue) 
    6 | } 
    7 | 

回答

2

您需要安裝babel-preset-stage-0作爲一個開發依賴這樣的:

npm install --save-dev babel-preset-stage-0

,最好是在documentation提到你需要把它添加到.babelrc文件,(你可以創建一個.babelrc文件的根目錄相同的地方webpack.config.js是),並添加這樣的:

{"presets":["react", "es2015", "stage-0"]} 

或者,如果你如果您正在使用webpack.config.js,則可以在您的查詢對象中使用:

query: {presets:["react", "es2015", "stage-0"]} 
+0

我認爲這可能已經成功了!在我能夠編譯之前,我需要解決一些其他問題。我會盡快告訴你。 – Nick

+0

多數民衆贊成在罰款,任何問題讓我知道:) – Aaqib

+1

這樣做了!謝謝! – Nick

0

您將需要添加transform-class-properties plugin
並將其添加到通天的配置:

{ 
    "plugins": [ 
    "transform-class-properties" 
    ] 
} 
+0

感謝您的回覆。我做了你所建議的改變,但我現在得到了「缺少類屬性轉換」。錯誤在同一行上。 – Nick

+1

您是否使用webapck並在您的webpack加載器中使用babel的其他配置? –

+0

我擁有的唯一配置是我在問題中發佈的配置。 – Nick