【问题标题】:React-navigation 5x usage of Stack.Screen screenPropsReact-navigation 5x 使用 Stack.Screen screenProps
【发布时间】:2020-05-27 21:48:24
【问题描述】:

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

【问题讨论】:

  • 对于您的下一个问题,您可能希望使用 react-navigation 标记您的问题,以便更多人可以看到它。

标签: react-native react-navigation-v5


【解决方案1】:

在我的情况下,我正在传递我的数据,例如:

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

你可以像这样访问它:

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

【讨论】:

  • 谢谢我的朋友,但我不是这个过程的意思。我想知道如何在 by screenProps 中做到这一点
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    渲染回调以返回用于屏幕的 React Element:

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

    如果你需要传递额外的 props,你可以使用这种方法来代替组件 props。虽然我们建议使用 React 上下文来传递数据。

    注意:默认情况下,React Navigation 会对屏幕组件进行优化,以防止不必要的渲染。使用渲染回调会删除这些优化。因此,如果您使用渲染回调,则需要确保为屏幕组件使用 React.memoReact.PureComponent 以避免性能问题。

    这是我目前使用的:

    // ...
    
    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>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      相关资源
      最近更新 更多