在使用react 0.14的ES6时,有没有避免样板的方法?
直到现在,我并不需要担心自己的函数会被绑定到我创建的Component
上,但现在已经不是了(为什么?!)情况和组件仅限于Component
超类(如果我正确理解错误的话)。
因此,每次创建新类时,我真正需要做的是将这些代码添加到构造函数中:
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
,它将失败(没有道具、状态或任何东西)。
有办法解决这个问题吗?
发布于 2015-11-07 04:22:24
来自反应文件
无自动绑定 方法遵循与常规ES6类相同的语义,这意味着它们不会自动将其绑定到实例。您必须显式地使用.bind(此)或箭头函数=>。
因此,不存在绑定0.14中所有新方法的自动方法。但是,如文档所示,您可以:
1)使用箭头函数(但是,如果您使用的是Babel,则需要)
class CustomComp extends React.Component {
constructor() {
super();
}
newFunction = () => {
console.log('This is user defined function');
}
render() {
return <button onClick={this.newFunction}>Click</button>
}
}
2)可以在place中绑定
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)您可以使用箭头函数 in (与绑定类似):
class CustomComp extends React.Component {
constructor() {
super();
}
newFunction() {
console.log('This is user defined function');
}
render() {
return <button onClick={() => this.newFunction()}>Click</button>
}
}
如果我只有1-2个方法,我倾向于使用数字2&3。数字1很好,但是您必须记住每个方法定义的语法。如果我有很多方法,我确实倾向于在构造函数中绑定。
https://stackoverflow.com/questions/33582605
复制相似问题