我想根据调用的函数设置动态状态,我知道如果我们不能在渲染中setstate
,但我仍然需要这样做来设置动态状态,
有什么方法可以实现吗?
export default class Foo extends Component {
constructor(props) {
super(props);
this.state={
dynamicView:false
}
}
renderText(key, value){
this.setState({[key]:value})
<Text>Simple render</Text>
}
renderButton(key, value){
this.setState({[key]:value})
<Text>Simple render</Text>
}
render(){
return(
<View>
{this.state.dynamicView ? this.renderButton("button","ValueButton") : this.renderText("text", "valueText")}
<Button
title="change Component"
onPress={()=>this.setState({dynamicView:!this.state.dynamicView})}
/>
<Button
title="Isi State"
onPress={()=>alert(JSON.stringify(this.state,null,4))}
/>
</View>
)
}
}
使用这些代码我可以设置动态状态,但问题是当两个组件函数
被调用时,我有两个状态(按钮和文本)
,我想要为了避免这种情况,所以我只有 1 个状态 (button/text)
取决于显示的组件,
我该怎么做?
Note: this is just a simple use-case, all i need to know is to set state depend on which function is called
最佳答案
如果您只想保留按钮或文本状态,那么您应该考虑更改其他状态。
renderText(key, value){
this.setState({[key]:value})
this.setState({button:false})
<Text>Simple render</Text>
}
关于android - 如何 setState() 取决于调用哪个组件 func?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283123/