android - 如何 setState() 取决于调用哪个组件 func?

标签 android react-native setstate

我想根据调用的函数设置动态状态,我知道如果我们不能在渲染中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/

相关文章:

android - android中具有相同时间间隔的多个服务

android - 水平 RecyclerView 与 ViewPager

android - 为什么 Toolbar 会被 TabLayout 覆盖?

react-native - 类型错误 : undefined is not an object (evaluating '_reactNativeImagePicker.default.showImagePicker' )

javascript - 我应该如何为以下对象正确使用 setState

android - React Native Picker 不更新状态

android - 如何使微调器宽度与最大可用项目宽度相同

android - ZipException : duplicate entry: com/google/android/gms/internal/measurement/zzwn. 类

ios - 如何将苹果付款通知与我的自定义付款记录关联?

reactjs - React 组件不在 setState 上重新渲染