繁体   English   中英

setState()如何取决于调用哪个组件函数?

[英]How to setState() depend on which component func is called?

我想设置取决于哪个函数被调用动态状态,我知道,如果我们不能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)具体取决于显示哪个组件,

我怎样才能做到这一点?

注意:这只是一个简单的用例,我所需要知道的是根据调用哪个函数来设置状态

如果只想保留按钮状态或文本状态,则应考虑更改其他状态。

    renderText(key, value){
    this.setState({[key]:value})
    this.setState({button:false})
    <Text>Simple render</Text>
  }

我认为您需要状态中的另一个变量,并根据基于dynamicView的条件触发的功能对其进行更新。

export default class Foo extends Component {
  constructor(props) {
  super(props);
   this.state={
     dynamicView:false,
     viewType:''
   }
 }
  renderText(viewType){
    this.setState(viewType)
    <Text>Simple render</Text>
  }

 renderButton(viewType){
   this.setState({viewType})
   <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>
  )
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM