首页 文章

如何在React Native Navigation v2中更新自定义顶栏 Headers 组件?

提问于
浏览
0

我正在尝试更新自定义topBar Headers 组件后,它已经变得可见 . 我试过调用Navigation.mergeOptions并使用passProps没有运气 .

初始选项:

...
static options(passProps) {
  return {
    topBar: {
      title: {
        component: {
          id: "rn.MyCustomTopBar",
          name: "rn.MyCustomTopBar",
          alignment: "fill",
          passProps: {
            dynamicField: "Initial Value"
          }
        }
      }
    }
  };
}
...

使用mergeOptions:

...
Navigation.mergeOptions(this.props.componentId, {
  topBar: {
    title: {
      component: {
        passProps: {
          dynamicField: "New Value"
        }
      }
    }
  }
});
...

在GitHub上似乎有一个关于自定义组件的合并选项的封闭问题https://github.com/wix/react-native-navigation/issues/3782,说它将在#3030中解决,但该问题没有里程碑,自6月以来没有任何活动 . https://github.com/wix/react-native-navigation/issues/3030

如果任何人都可以提供一个解决方案,并举例说明如何实现这一点,我们将不胜感激 .

1 回答

  • 0

    可以通过passProps将引用传递回父级来更新自定义顶栏 . 然后,父级可以使用引用来调用顶部栏中的一个函数,该函数将适当地更改其状态 .

    父组件:

    ...
    constructor() {
      super(props);
      Navigation.events().bindComponent(this);
    
      this._customTopBar = null;
    }
    ...
    componentDidMount() {
      Navigation.mergeOptions(this.props.componentId, {
        topBar: {
          title: {
            component: {
              passProps: {
                passRef: ref => {
                  this._customTopBar = ref;
                }
              }
            }
          }
        }
      });
    }
    ...
    // called whenever custom title needs to be updated
    this._customTopBar.updateState(...);
    ...
    

    自定义组件:

    ...
    componentDidMount() {
      this.props.passRef(this);
    }
    ...
    updateState(...) {
      this.setState(...);
    }
    ...
    

    注意:这尚未在Android上进行过测试 .

相关问题