【发布时间】:2021-11-07 01:08:43
【问题描述】:
当我想让我的类函数的this 绑定到类(组件)实例时,我会这样做。在 React 中有没有更简单/更合适的方法来做到这一点?
class App extends Component {
state = {
currentSection: 1,
message :{text:''}
};
constructor(props) {
super(props);
this.prevSection = this.prevSection.bind(this);
this.nextSection = this.nextSection.bind(this);
this.mobileChanged = this.mobileChanged.bind(this);
}
}
【问题讨论】:
-
另一种选择是不使用类。然后你可以避免使用
this。像您所做的那样使用绑定将使原型上的方法可用。如果在调用构造函数之前不关心方法是否可以访问,请使用箭头函数。 stackoverflow.com/questions/31362292/…
标签: javascript reactjs ecmascript-6