简体   繁体   English

如何使this.forceUpdate()应用于React Native中的整个应用程序?

[英]How do you make this.forceUpdate() apply to entire app in React Native?

I have a React Native app in which I want to place a button that appears on every screen that the user can click to force a re-render (using this.forceUpdate() ). 我有一个React Native应用程序,我想在其中放置一个按钮,该按钮出现在用户可以单击以强制重新渲染的每个屏幕上(使用this.forceUpdate() )。 On every screen I have a custom <Header> component at the top, and I want to put the re-render button in that header since it appears on every screen, and I'd therefore have to add the button only once. 在每个屏幕上,我都在顶部有一个自定义的<Header>组件,并且由于每个屏幕上都出现了重新渲染按钮,因此我想在该标题中放置一个按钮,因此,我只需要添加一次按钮即可。

So one of my screens would look like this: 因此,我的屏幕之一如下所示:

export default class Screen1 extends Component {
  render() {
    return(
      <View>
        <Header>
        ...rest of screen...
      </View>
    )
  }
}

And Header looks like this Header看起来像这样

export default class Header extends Component {
  render(){
    return(
      <View>
        <TouchableOpacity
          onPress={() => this.forceUpdate()}
        />
      </View>
    )
  }
}

Clicking the <TouchableOpacity> in the Header causes the Header itself to update, but not the entire screen. 单击标题中的<TouchableOpacity>会使标题本身更新,而不是整个屏幕。 I assume this.forceUpdate() applies only to the component in which the <TouchableOpacity> is defined. 我假设this.forceUpdate()仅适用于定义了<TouchableOpacity>的组件。 So my question is, is there any equivalent of this.forceUpdate() that I can call in my header that will force a re-render of the entire screen? 所以我的问题是, 我可以在标头中调用this.forceUpdate()任何等效项,以强制重新渲染整个屏幕吗?

Thanks! 谢谢!

As @parohy suggested it's not the way to go.. at all. 正如@parohy所建议的那样,这根本不是路。
But has a temporary hack you can pass this.forceUpdate() as props to the header. 但是有一个临时的技巧,您可以将this.forceUpdate()作为道具传递给标头。
would look like this: 看起来像这样:

 export default class Screen1 extends Component {
  render() {
    return(
      <View>
        <Header forceUpdate={this.forceUpdate}>
        ...rest of screen...
      </View>
    )
  }
}
export default class Header extends Component {
  render(){
    return(
      <View>
        <TouchableOpacity
          onPress={() => this.props.forceUpdate()}
        />
      </View>
    )
  }
}

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

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