如果我们在文档示例中看到: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
?
答案 0 :(得分:1)
您必须具有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>
);
}