2015-11-07 52 views
6

使用ES6时反应0.14是否有避免样板的方法?React仅将组件方法绑定到此 - 解决方法?

到现在为止,我不必担心我的函数被绑定到我创建的Component,但这不再是(为什么?!?)的情况和Component仅限于Component超类(If我正确理解错误)。

所以我真的需要每个创建一个新的类就是这个代码添加到构造时间做:

class CustomComp extends React.Component { 

    constructor() { 
    super(); 
    this.newFunction = this.newFunction.bind(this); 
    } 

    newFunction(){ 
    console.log('This is user defined function'); 

} 
    render() { 
    return <button onClick={this.newFunction}>Click</button> 
    } 
} 

所以,如果我不会绑定newFunction它会失败(无道具,状态或任何)。

有没有办法解决这个问题?

+0

https://medium.com/@john1jan/react-binding-revealed-aa458df8c136#.fd5z0vmjl – John

回答

5

React documentation

没有自动绑定

方法遵循相同的语义规则ES6类,这意味着 它们不会自动绑定到这个实例。你必须明确地使用.bind(this)或者arrow functions =>来使用 。

因此,不,没有一种自动方式来绑定0.14中新增的所有方法。但是,正如文档建议,用户可以:

1)使用箭头功能(但是,如果使用的是巴别,需要阶段0)

class CustomComp extends React.Component { 

    constructor() { 
    super(); 
    } 

    newFunction =() => { 
    console.log('This is user defined function'); 

} 
    render() { 
    return <button onClick={this.newFunction}>Click</button> 
    } 
} 

2),则可以在地方绑定

class CustomComp extends React.Component { 

    constructor() { 
    super(); 
    } 

    newFunction() { 
    console.log('This is user defined function'); 

} 
    render() { 
    return <button onClick={this.newFunction.bind(this)}>Click</button> 
    } 
} 

3)您可以使用AR代替行功能(这是如结合):

class CustomComp extends React.Component { 

    constructor() { 
    super(); 
    } 

    newFunction() { 
    console.log('This is user defined function'); 

} 
    render() { 
    return <button onClick={() => this.newFunction()}>Click</button> 
    } 
} 

我倾向于使用数2 & 3如果我只有一个1-2的方法。数字1是好的,但你必须记住每个方法定义的语法。如果我有很多方法,我确实倾向于在构造函数中绑定。

+1

很好的答案。只需稍微提示一下:你可以跳过额外的{{}'集合,然后直接写'onClick = {()=> this.newFunction()}'。 – naomik

+0

@naomik是的。你是对的。编辑。谢谢。 –

+0

很好的答案。谢谢。 – Shikloshi