我有一个案例,我有一个嵌套的导航器设置.app.js持有loggedIn状态,导航器的启动方式为:app.js中调用startnav,传递loggedIn状态。
class StartupNav extends Component {
constructor(props) {
super(props);
console.log(props.loggedIn);
}
render() {
return (
<NavigationContainer independent={true}>
<Stack.Navigator>
{this.props.loggedIn ? (
<>
<Stack.Screen name="MainContainer" component={MainContainer} />
</>
) : (
<Stack.Screen
name="AuthStack"
component={AuthStack}
params="that" //props pass attempt which isnt successful
/>
)}
</Stack.Navigator>
</NavigationContainer>
);
}
}
export default StartupNav;
authStack持有登录部分为 。
class AuthStack extends Component {
constructor(props) {
super(props);
console.log('props from authstack', props);
}
render() {
return (
<NavigationContainer independent={true}>
<Stack.Navigator>
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="ForgotPassword" component={ForgotPassword} />
</Stack.Navigator>
</NavigationContainer>
);
}
}
然后是登录界面,我在这里做登录逻辑,并尝试在app.js中设置loggedIn=true的状态。登录成功后,我需要打开MainContainer,其中包含了登录应用的屏幕。
我无法将道具从上层的navScreen传递到下层,这样我就可以在登录成功时调用道具函数。我试着在代码中注释,就像我们通常做的那样,但这甚至是无效的。有人能给我一个光,或者给我指出正确的方向。
我使用的是react导航5。
我想你可以使用context(https:/reactjs.orgdocscontext.html。)
我在这里做了一个小吃的例子 https:/snack.expo.iowzqRLEbi4
const LoginContext = React.createContext({
loggedIn: false,
setLogin: () => {},
setLogout: () => {}
});
export default class App extends Component {
constructor(props) {
super(props);
this.setLogin = () => {
this.setState({
loggedIn: true
})
};
this.setLogout = () => {
this.setState({
loggedIn: false
})
};
// State also contains the updater function so it will
// be passed down into the context provider
this.state = {
loggedIn: false,
setLogin: this.setLogin,
setLogout: this.setLogout
};
}
render() {
return (
<LoginContext.Provider value={this.state}>
<NavigationContainer independent={true}>
<Stack.Navigator>
{this.state.loggedIn ? (
<>
<Stack.Screen name="MainContainer" component={MainContainer} />
</>
) : (
<Stack.Screen
name="AuthStack"
component={AuthStack}
params="that" //props pass attempt which isnt successful
/>
)}
</Stack.Navigator>
</NavigationContainer>
</LoginContext.Provider>
);
}
}
class Login extends Component {
tryLogin = (setLogin) => {
// your login logic
let isLoginSuccess = true;
// if success
setLogin();
}
render() {
return (
<LoginContext.Consumer>
{({setLogin}) => (
<View style={{justifyContent: 'center', alignItems: 'center'}}>
<TouchableOpacity onPress={() => this.tryLogin(setLogin)}><Text>Login</Text></TouchableOpacity>
</View>
)}
</LoginContext.Consumer>
)
}
}