如何使用React Navigation仍然呈现组件时更新标题?

问题描述 投票:1回答:2

我正在编写一个React Native应用程序,我正在使用React Navigation(V2)。在我的组件更新后,我想更新navigationOptions并添加一个新按钮。这是我尝试过的代码:

  static navigationOptions = ({ navigation }) => {
    const options = {
      headerTitle: SCREEN_TEXT_MENU_HEADER,
      headerStyle: {
        borderBottomWidth: 0,
        marginBottom: -5
      }
    };
    if (navigation.getParam("drawer", true)) {
      options["headerLeft"] = (
        <HeaderIconButton
          onClick={() => {
            navigation.openDrawer();
          }}
          icon={require("../../assets/icons/burgerMenu.png")}
        />
      );
    }
    if (navigation.getParam("renderBillButton", false)) {
      options["headerRight"] = (
        <HeaderIconButton
          onClick={() => {
            navigation.navigate("BillScreen");
          }}
          type="primary"
          icon={require("../../assets/icons/euro.png")}
        />
      );
    }
    return options;
  };

  componentDidUpdate = prevProps => {
    const { navigation, orders } = this.props;
    if (prevProps.orders.length !== orders.length) {
      navigation.setParams({
        renderBillButton: orders.length > 0
      });
    }
  };

这种方法的问题是,navigationOptionscomponentDidUpdate()之后不会被重置。如何使用React Navigation动态调整标题?

react-native header react-navigation react-lifecycle
2个回答
0
投票

您可以使用this.props.navigation.setParams()函数来更新导航状态参数。

参考:https://reactnavigation.org/docs/en/headers.html#updating-navigationoptions-with-setparams


0
投票

好的,这里出了什么问题:我还必须在componentDidMount()中调用相同的代码,否则在加载时不会影响页面。所以除了我的问题的代码,我补充说:

componentDidMount = () => {
  const { navigation, order } = this.props;
  navigation.setParams({
    renderBillButton: orders.length > 0
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.