【问题标题】:How to update the header while the component is still rendered using React Navigation?如何在组件仍使用 React Navigation 呈现时更新标题?
【发布时间】:2018-08-16 13:47:32
【问题描述】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 但这就是我所做的!你读过我的代码吗?或者你的意思是不同的方式?
    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2019-01-28
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2023-01-25
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多