React Navigation v5身份验证流程(屏幕为不同文件)

时间:2020-06-13 13:34:37

标签: react-native react-hooks use-reducer react-usememo

如果我们在文档示例中看到: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

1 个答案:

答案 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>
  );
}