如何将组件道具传递给react-navigation的静态navigationOptions函数

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

我有一个react组件类,它通过static navigationOptions函数声明一个自定义的react-navigation标头,react-navigation然后自动调用。问题是,我想根据传递给组件的props有条件地呈现标题,而不是简单地将作为参数传递给路径的props。我不能简单地在componentDidMount上设置它们,因为我引用的道具在它安装的组件之后发生了变化,我需要将它们插入标题。

我想出了一种方法,并认为我会在这里发布。

reactjs react-native react-navigation
1个回答
1
投票

首先,一个辅助方法。这样做的目的只是为了确保当我们将props传递给componentDidUpdate中的navigation.params时,我们不会进入无限循环 - 并且封装实际映射prop的逻辑smidge。这使用JSON.stringify来比较道具。根据您正在做的事情,您可能需要使用更复杂的比较来替换该位。

export function mapPropsToNavigationRouteParams(
  props,
  prevProps,
  getPropsToMap,
) {
  if (!props) return;
  const propsToMap = getPropsToMap(props);

  if (
    !prevProps ||
    JSON.stringify(getPropsToMap(prevProps)) !== JSON.stringify(propsToMap)
  ) {
    props.navigation.setParams(getPropsToMap(props));
  }
}

然后,在上面提到的方法的组件中我们可以做这样的事情......

const getPropsToMapToNavigation = props => ({
  myComponentProp: props.myComponentProp,
});

class MyComponent extends React.Component {
  componentDidMount() {
    mapPropsToNavigationRouteParams(
      this.props,
      null,
      getPropsToMapToNavigation,
    );
  }

  componentDidUpdate(prevProps) {
    mapPropsToNavigationRouteParams(
      this.props,
      prevProps,
      getPropsToMapToNavigation,
    );
  }

  static navigationOptions = ({navigation}) => {
    const {params} = navigation.state;
    const myComponentProp = params ? params.myComponentProp : null;
    // ...
  }

考虑到react-router的限制,这是我能想到的最好的。如果您有更好的解决方案,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.