Stack.Screen screenProps 的 React-navigation 5 倍使用

React-navigation 5x usage of Stack.Screen screenProps

我想在 React-navigation v5.x.x 中通过 screenProps 传递一些东西。我是react-native的新人之一。谁能帮帮我?

在我的例子中,我正在传递我的数据:

props.navigation.navigate('toScreen', {
    resumeDetail: data,
})

您可以像这样访问它:

detail = this.props.navigation.state.params.resumeDetail;

React Navigation 5 中没有 screenProps。您可以使用 React's Context feature 来将数据向下传递到树中,而无需额外的 API。

https://reactnavigation.org/docs/upgrading-from-4.x#global-props-with-screenprops

https://reactnavigation.org/docs/screen/#children

Render callback to return React Element to use for the screen:

<Stack.Screen name="Profile">
 {(props) => <ProfileScreen {...props} />}
</Stack.Screen>

You can use this approach instead of the component prop if you need to pass additional props. Though we recommend using React context for passing data instead.

Note: By default, React Navigation applies optimizations to screen components to prevent unnecessary renders. Using a render callback removes those optimizations. So if you use a render callback, you'll need to ensure that you use React.memo or React.PureComponent for your screen components to avoid performance issues.

这是我目前使用的:

// ...

export const ScanPage = React.memo(ScanComponent);
function useScreenWithProps(
  PageComponent: React.FC<Props>,
  props: Props
) {
  // Take note of the double arrow,
  // the value useMemo returns is a function that returns a component.
  return useMemo(
    () => (navigationProps: NavigationProps) => (
      <PageComponent {...navigationProps} {...props} />
    ),
    [PageComponent, props]
  );
}

const Stack = createStackNavigator();

const Navigator: React.FC<Props> = (props) => {
  const scan = useScreenWithProps(ScanPage, props);
  const activate = useScreenWithProps(ActivatePage, props);
  const calibrate = useScreenWithProps(CalibratePage, props);
  const success = useScreenWithProps(SuccessPage, props);
  const error = useScreenWithProps(ErrorPage, props);

  return (
    <Stack.Navigator>
      <Stack.Screen name="Scan">{scan}</Stack.Screen>
      <Stack.Screen name="Activate">{activate}</Stack.Screen>
      <Stack.Screen name="Calibrate">{calibrate}</Stack.Screen>
      <Stack.Screen name="Success">{success}</Stack.Screen>
      <Stack.Screen name="Error">{error}</Stack.Screen>
    </Stack.Navigator>
  );
};