javascript - 在反应导航中将道具很好地传递到屏幕
问题描述
我想将道具传递到屏幕上。当我尝试该内联时,例如(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 组件,这意味着每次都会卸载旧组件并安装新组件。传递函数时会发生同样的事情,但没有警告
您不能将道具传递给这些屏幕,因为它不是Loading
这些屏幕的直接父组件。如果你想传递数据来定制这些组件,你需要通过导航参数来完成,有两种方式:
- 导航到屏幕时
navigation.navigate('Login', { param: 'hello' })
- 通过提供初始参数
.
<Stack.Screen
name="Login"
component={Loaing}
initialParams={{ param: 'hello' }}
/>
Login
并阅读它props.route.params
请注意,尽管这被称为 initialParams 是有原因的 - 它们不是反应性的,在安装组件后更改它们没有效果(也可以从组件内部更改它们)。如果要传递反应参数,请使用 React Context或 Redux
推荐阅读
- html - Visual Studio 2019 HTML 编辑器中的快速信息弹出窗口挂起
- r - 如何在 ggplot2 R 中为地理/位置质心绘制误差线?
- python - n_jobs for sklearn multioutput regressor with estimator=random forest regressor
- python - 在对数据框进行查询后创建虚拟变量
- django - 无法使用自定义帐户适配器
- javascript - 如何使量角器 JavaScript 等待读取文件完成?
- java - 如何在 IBM DB2 v11.1 中升级 Java(至少到 8.0.6.25 )
- javascript - 使用数组映射方法时删除以前的 DOM 元素
- kubernetes - Kubernetes,如何与其他节点共享读/写持久卷作为只读卷
- yaml - Nunjucks 不会读取带有缩进的 frontmatter