繁体   English   中英

在反应导航中将道具很好地传递到屏幕

[英]Pass props nicely to screens in react navigation

我想向屏幕传递一个道具。 当我尝试内联 eg (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>
      )}
    </>
  );
}
```

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

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

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

.

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

并在Login with props.route.params阅读它

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

将参数传递给路由

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM