当组件仍使用React Navigation呈现时,如何更新标头?

时间:2018-08-16 13:47:33

标签: react-native header react-navigation react-lifecycle

我正在编写一个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
      });
    }
  };

此方法的问题在于,navigationOptions之后componentDidUpdate()不会重置。如何使用React Navigation动态调整标题?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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