首页 > 解决方案 > React Native screen trying to export function

问题描述

New to React (and Native), I'm trying to modify this working Snack. I'm trying to move the SignInScreen to its own file and call it from the default App file, here is my SignInScreen file where the error is happening:

import * as React from 'react';
import { Button, View, TextInput } from 'react-native';

const context = React.createContext();

export function SignInScreen() {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');

  console.log(context);

  const {signIn} = React.useContext(context); //blows up here

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

Called via <Stack.Screen name="SignIn" component={SignInScreen}>

I'm getting an error:

Cannot read property 'signIn' of undefined at SignInScreen

I'm assuming this just an encapsulation (or syntax or scope) issue I don't understand.

标签: react-native

解决方案


您需要提供该signIn功能的实现。您可以在调用时执行此操作,也可以createContext将其作为该Provider上下文的值传递(假设您有一个,否则这是另一个问题)。

const context = createContext({
    signIn : ({ username, password }) => {
        console.log(username, password);
    }
});

我建议你稍微阅读一下文档。


推荐阅读