我有一个类,下面的ElementBuilder,当用户保存他们构建的元素时,我希望状态重置为下面的值.
我在这个类中有一些我没有提供但是改变标题,大小和颜色状态的函数.
在ES 5中,我在我的类上有一个getinitialState函数,可以在函数中调用this.getinitialState().
这个元素存在于我的应用程序中,用于登录用户的生命周期,我希望默认值始终相同,无论过去的用法如何.
如何在不编写设置默认值对象的函数(或者可能是答案)的情况下实现此目的?谢谢!
class ElementBuilder extends Component {
constructor(props) {
super(props);
this.state = {
title: 'Testing,size: 100,color: '#4d96ce',};
}
resetBuilder() {
this.setState({ this.getinitialState() });
}
}
解决方法
您可以使用getter函数:
class ElementBuilder extends Component {
constructor(props) {
super(props);
this.state = this.initialState;
}
get initialState() {
return {
title: 'Testing',};
}
resetBuilder() {
this.state(this.initialState);
}
}
或只是一个变量:
constructor(props) {
super(props);
this.initialState = {
title: 'Testing',};
this.state = this.initialState;
}