![](/img/trans.png)
[英]unable to pass navigation props b/w screens with react-navigation
[英]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
組件。 如果你想傳遞數據來自定義這些組件,你需要通過導航參數來完成,有兩種方式:
navigation.navigate('Login', { param: 'hello' })
.
<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.