1

如果我们在文档示例中看到: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.jsSignInScreen作为一个新文件发布,如何从SignInScreen.js调度?signIn

4

1 回答 1

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>
  );
}
于 2020-06-13T13:56:55.617 回答