【发布时间】:2019-01-21 03:22:06
【问题描述】:
我想根据调用的函数设置动态状态,我知道我们是否不能在渲染中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>
)
}
}
使用这些代码我可以设置动态状态,但问题是在调用 component function 时,我有两个状态 (button and text),我想避免这种情况,所以我只有 1 个状态 (button / text) 取决于显示哪个组件,
我该怎么做?
注意:这只是一个简单的用例,我只需要知道设置状态取决于调用哪个函数
【问题讨论】:
标签: android react-native setstate