如何在组件仍在使用 React Navigation 呈现时更新 header?

How to update the header while the component is still rendered using React Navigation?

我正在编写一个 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 动态调整 header?

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

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

好的,这就是问题所在:我还必须在 componentDidMount() 中调用相同的代码,否则它不会在加载时影响页面。所以除了我的问题代码外,我还添加了:

componentDidMount = () => {
  const { navigation, order } = this.props;
  navigation.setParams({
    renderBillButton: orders.length > 0
  });
}