Es6 React Arrow function behaviour

Im am trying to get into react using borwserify, watchify, babelfiy (with es2015 preset).

Could please anyone explain, why this is working:

export default class HelloWorld extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        username: 'Tyler McGinnis'
    }

    this.handleChange = (e) => {
        this.setState({username: e.target.value})
    };


}

render() {

    return (
        <div>
            Hello {this.state.username} <br />
            Change Name: <input type="text" value={this.state.username} onChange={this.handleChange} />
        </div>
    )
}

while this is not (arrow function outside constrcutor)

export default class HelloWorld extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        username: 'Tyler McGinnis'
    }
}


handleChange = (e) => {
   this.setState({username: e.target.value})
};

render() {

    return (
        <div>
            Hello {this.state.username} <br />
            Change Name: <input type="text" value={this.state.username} onChange={this.handleChange} />
        </div>
    )
}

the last one gives me an error, that is:

Unexpected token (18:17)

handleChange = ((e) => {
            ^
       this.setState({username: e.target.value})
} );

All i can find on the internet tells me, that both syntax should work, but they dont. this happens with the es2015 babel preset set correctly (proof by compiling version one without an issue).

What am i missing? why cant i have an arrow function outside the constructor (or propably any other "regular" function in the class)? Any help appreciated!


In ES6 / ES2015 you can't have arrow functions as a class method.

Define handleChange as normal method.

handleChange(e){
   this.setState({username: e.target.value});
}

Bind handleChange with this in the constructor function

constructor() {
    this.handleChange = this.handleChange.bind(this);
}

这是一个名为Class properties transform的ES7 stage-1特性,您可以安装babel-preset-stage-1或使用插件transform-class-properties使其工作。

链接地址: http://www.djcxy.com/p/32948.html

上一篇: 带有browserify和babelify的JavaScript ES2015动态继承

下一篇: Es6反应箭头功能行为