Pass props nicely to screens in react navigation

白昼怎懂夜的黑 提交于 2021-01-07 02:44:57

问题


I want to pass a prop to the screen. When I try that inline e.g (props) => <Comp {...props} {...customProps} /> I get a warning message, that I shouldn't parse functions to that component property. Okay. I thought I'll just create functions for every component which needs custom props. It is working, but is there a better solution? Here is my component:

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

回答1:


Yours is not a good solution to the problem because new types of LoginWithProps and RegistrationWithProps components will be created every render, meaning old ones will be unmounting and new ones mounting every time. The same thing that happens when you pass a function, but without a warning

You can't pass props to these screens, as it is not the Loading component that is a direct parent to these screens. If you want to pass data to customize those components, you need to do it through navigation params, in 2 ways:

  1. when navigating to a screen navigation.navigate('Login', { param: 'hello' })
  2. by proviging initial params

.

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

And read it in Login with props.route.params

Note though this is called initialParams for a reason - they are not reactive, changing them after component is mounted has no effect (it is also possible to change them from inside component). If you want to pass reactive params, use React Context or Redux

Passing parameters to routes



来源:https://stackoverflow.com/questions/60892552/pass-props-nicely-to-screens-in-react-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!