首页 > reactjs中如何正确使用ES6的=>(箭头函数)?

reactjs中如何正确使用ES6的=>(箭头函数)?

class MyComponent extends React.Component {
    handleClick() {
        this.refs.myTextInput.focus();
    }

    render() {
        return (
            <div>
                <input type="text" ref="myTextInput"/>
                //如何使用箭头函数改写从而省略这里的 bind(this)
                <input type="button" value="Focus the text input" onClick={this.handleClick.bind(this)}/>
            </div>
        );
    }
}
class Input extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: 'Hello!'};
    }

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

    render() {
        var value = this.state.value;
        return (
            <div>
            //如何使用箭头函数改写从而省略这里的 bind(this)
                <input type="text" value={value} onChange={this.handleChange.bind(this)}/>
                <p>{value}</p>
            </div>
        );
    }
}

使用箭头函数的话,一般是就在那个位置写执行代码。
而比如说已经有一个function定义好了,那还是用bind来做吧。


或者你这里试试这样写

onClick={event=>this.handleClick(event)}

可以通通放到 constructor 里面绑定


箭头函数是箭头函数,bind this 是bing this,是两个东西。

题主的“如何使用箭头函数改写从而省略这里的 bind(this)”是错误的。

省略this的优美方案是引入es7的:: 在 babel中把stage-0引入即可。

class MyComponent extends React.Component {
    render() {
        return (
            <div>
                <input type="text" ref="myTextInput"/>
                //如何使用箭头函数改写从而省略这里的 bind(this)
                <input type="button" value="Focus the text input" onClick={() => {this.refs.myTextInput.focus()}}/>
            </div>
        );
    }
}
【热门文章】
【热门文章】