如何在 React Native 中引用 header 组件
How to reference a header component in React Native
我正在制作一个 React Native 应用程序,用户可以在其中对某些主题发表评论。我有一个在 header 中带有自定义 <SubscribeButton />
的堆栈导航器。
当用户查找主题时,他们可以单击按钮以(取消)订阅,按钮的布局会相应改变。 (un)subscribe 的逻辑和服务器调用都在自定义组件中。
我现在想做的是让用户在对主题发表评论时自动订阅。通常,我会使用 ref={ref => this._subscribeButton = ref}
引用此自定义组件,然后调用 this._subscribeButton.subscribe()
。但是,由于该组件位于 stacknavigator 的 header 中,我似乎无法引用它并且引用的计算结果为 undefined。
有什么好的方法可以解决这个问题吗?
谢谢!
找到解决方案:
而不是用 'this' 引用 header 组件,它们可以用 'navigation':
引用
<MyComponent
ref={myComp => navigation.myComp = myComp}
/>
只需调用:
this.props.navigation.myComp.subscribe()
我正在制作一个 React Native 应用程序,用户可以在其中对某些主题发表评论。我有一个在 header 中带有自定义 <SubscribeButton />
的堆栈导航器。
当用户查找主题时,他们可以单击按钮以(取消)订阅,按钮的布局会相应改变。 (un)subscribe 的逻辑和服务器调用都在自定义组件中。
我现在想做的是让用户在对主题发表评论时自动订阅。通常,我会使用 ref={ref => this._subscribeButton = ref}
引用此自定义组件,然后调用 this._subscribeButton.subscribe()
。但是,由于该组件位于 stacknavigator 的 header 中,我似乎无法引用它并且引用的计算结果为 undefined。
有什么好的方法可以解决这个问题吗?
谢谢!
找到解决方案:
而不是用 'this' 引用 header 组件,它们可以用 'navigation':
引用<MyComponent
ref={myComp => navigation.myComp = myComp}
/>
只需调用:
this.props.navigation.myComp.subscribe()