React Navigation v5 身份验证流程(屏幕显示为不同的文件)
React Navigation v5 Authentication Flows (Screens as Different Files)
如果我们在文档示例中看到:https://reactnavigation.org/docs/auth-flow/ :
function SignInScreen() {
const [username, setUsername] = React.useState('');
const [password, setPassword] = React.useState('');
const { signIn } = React.useContext(AuthContext); // ????
return (
<View>
<TextInput
placeholder="Username"
value={username}
onChangeText={setUsername}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button title="Sign in" onPress={() => signIn({ username, password })} />
</View>
);
}
SignInScreen
位于同一个 App.js。如果我们将 SignInScreen
作为一个新文件 SignInScreen.js 输出,如何从 SignInScreen.js[ 调度 signIn
?
您必须有 SignInScreen
的包装器
// App.js
import SignInScreen from '...'
// Export the context
export const AuthContext = React.createContext();
export default function App() {
// ... some bootstrap code
// https://reactnavigation.org/docs/auth-flow/#implement-the-logic-for-restoring-the-token
const authContext = React.useMemo(
() => ({
signIn: async (data) => { ... },
}),
[]
);
return (
<AuthContext.Provider value={authContext}>
<SignInScreen />
</AuthContext.Provider>
);
}
import { AuthContext } from "./App.js"
function SignInScreen() {
// Must be child of AuthContext.Provider
const { signIn } = React.useContext(AuthContext);
return (
<View>
...
</View>
);
}
如果我们在文档示例中看到:https://reactnavigation.org/docs/auth-flow/ :
function SignInScreen() {
const [username, setUsername] = React.useState('');
const [password, setPassword] = React.useState('');
const { signIn } = React.useContext(AuthContext); // ????
return (
<View>
<TextInput
placeholder="Username"
value={username}
onChangeText={setUsername}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<Button title="Sign in" onPress={() => signIn({ username, password })} />
</View>
);
}
SignInScreen
位于同一个 App.js。如果我们将 SignInScreen
作为一个新文件 SignInScreen.js 输出,如何从 SignInScreen.js[ 调度 signIn
?
您必须有 SignInScreen
// App.js
import SignInScreen from '...'
// Export the context
export const AuthContext = React.createContext();
export default function App() {
// ... some bootstrap code
// https://reactnavigation.org/docs/auth-flow/#implement-the-logic-for-restoring-the-token
const authContext = React.useMemo(
() => ({
signIn: async (data) => { ... },
}),
[]
);
return (
<AuthContext.Provider value={authContext}>
<SignInScreen />
</AuthContext.Provider>
);
}
import { AuthContext } from "./App.js"
function SignInScreen() {
// Must be child of AuthContext.Provider
const { signIn } = React.useContext(AuthContext);
return (
<View>
...
</View>
);
}