React Navigation v5身份验证流程(屏幕为不同文件) [英] React Navigation v5 Authentication Flows (Screens as Different Files)

查看:319
本文介绍了React Navigation v5身份验证流程(屏幕为不同文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们在文档示例中看到: https://reactnavigation.org/docs/auth-流量/:

If we see in the doc example: 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 is located in the same App.js. If we put out SignInScreen as a new file SignInScreen.js, how to dispatch the signIn from SignInScreen.js?

推荐答案

您必须具有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>
  );
}

这篇关于React Navigation v5身份验证流程(屏幕为不同文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆