我想知道如何处理依赖于另一个属性的组件状态中的属性,例如:
class Sample extends Component {
constructor(props) {
super(props);
this.state = {
mainProperty: 1,
something: {
dependingOnMainProperty: `foo${this.state.mainProperty}bar`
}
}
}
}
基本上,当我将dependingOnMainProperty
更改为mainProperty
时,我希望setState
自动更新。我应该为此编写一个函数还是有其他解决方案?
答案 0 :(得分:0)
您可以按照以下方式使用getter和setter;
class Component {
constructor(...props){
props.forEach(prop => this[prop] = "whatever");
}
}
class Sample extends Component {
constructor(...props) {
super(...props);
this.state = {
something: {
__mp__: "tester",
dependingOnMainProperty: `foo${this.mainProperty}bar`,
get mainProperty(){
return this.__mp__;
},
set mainProperty(v){
this.__mp__ = v;
this.dependingOnMainProperty = `foo ${v} bar`;
}
}
};
}
}
var s = new Sample("a", "b");
s.state.something.mainProperty = "hello";
console.log(s.state.something.dependingOnMainProperty);