首页 > 解决方案 > 在反应导航中将道具很好地传递到屏幕

问题描述

我想将道具传递到屏幕上。当我尝试该内联时,例如(props) => <Comp {...props} {...customProps} />我收到一条警告消息,我不应该将函数解析为该组件属性。好的。我以为我会为每个需要自定义道具的组件创建函数。它正在工作,但有更好的解决方案吗?这是我的组件:

export default function Loading() {
  const [loggedIn, setLoggedIn] = React.useState(false);
  const Stack = createStackNavigator();
  const authService: AuthService = new AuthService();
  const authProps: IAuthProps = {
    authService
  };
  /**
   * Bind neccessary props to the login component
   * @param props Props
   */
  function LoginWithProps(props) {
    return <Login {...props} {...authProps} />;
  }
  /**
   * Bin neccessary props to the registration component
   * @param props Props
   */
  function RegistrationWithProps(props) {
    return <Registration {...props} {...authProps} />;
  }
  return (
    <>
      {/*Show the app, when logged in*/}
      {loggedIn === true ? (
        <View>
          <Text>Test</Text>
        </View>
      ) : (
        <Stack.Navigator
          initialRouteName="Login"
          screenOptions={{ headerShown: false, animationEnabled: false }}
        >
          <Stack.Screen name="Login" component={LoginWithProps} />
          <Stack.Screen name="Registration" component={RegistrationWithProps} />
        </Stack.Navigator>
      )}
    </>
  );
}
```

标签: javascriptreactjsreact-nativereact-navigation

解决方案


你的方法不是解决问题的好方法,因为每次渲染都会创建新类型的 LoginWithProps 和 RegistrationWithProps 组件,这意味着每次都会卸载旧组件并安装新组件。传递函数时会发生同样的事情,但没有警告

您不能将道具传递给这些屏幕,因为它不是Loading这些屏幕的直接父组件。如果你想传递数据来定制这些组件,你需要通过导航参数来完成,有两种方式:

  1. 导航到屏幕时navigation.navigate('Login', { param: 'hello' })
  2. 通过提供初始参数

.

<Stack.Screen
  name="Login"
  component={Loaing}
  initialParams={{ param: 'hello' }}
/>

Login并阅读它props.route.params

请注意,尽管这被称为 initialParams 是有原因的 - 它们不是反应性的,在安装组件后更改它们没有效果(也可以从组件内部更改它们)。如果要传递反应参数,请使用 React Context或 Redux

将参数传递给路由


推荐阅读