[英]How to pass parameters of a function using Context API + Hooks in React Native
I'm using function component together with context api and hooks, I would like to know how to pass values to be accessed by useContext by passing a function我正在使用 function 组件以及上下文 api 和钩子,我想知道如何通过传递 ZC1C425268E68385D1AB5074C17A94F1Z4 来传递要由 useContext 访问的值
interface User{
user: string;
pass: string:
}
export const AuthProvider: React.FC = ({children}) => {
const [user, setUser] = useState<User | null>(null);
async function signIn(user : string, pass: string){
const response = await auth.signIn() ;
setUser(response.user);
}
return(
<AuthContext.Provider value={{signIn}}>
{children}
</AuthContext.Provider>
)
}
the error is in 'value={{signIn}}'错误在'value = {{signIn}}'
Type '(user: string) => Promise<void>' is not assignable to type '() => Promise<void>'.ts(2322)
auth.tsx(18, 5): The expected type comes from property 'signIn' which is declared here on type 'AuthContextData'
I'm using inside a component:我在组件内部使用:
const SignIn: React.FC = () => {
const {signIn} = useContext(Context);
const [userIn, setUser] = useState('');
const [passIn, setPass] = useState('');
async function handleSignIn(){
await signIn(userIn, passIn);
}
return (
<View style={styles.container}>
<TextInput onChangeText={text => setUser(text)} placeholder='User'></TextInput>
<TextInput onChangeText={text => setPass(text)} secureTextEntry={true} placeholder='Password'></TextInput>
<TouchableOpacity style={styles.button} onPress={handleSignIn}>
<Text style={styles.textButton}>Sign In</Text>
</TouchableOpacity>
</View>
)
}
export default SignIn;
problem solved, it was just changing the interface used by AuthContext问题解决了,只是改变了 AuthContext 使用的接口
interface AuthContextData {
user: User | null;
loading: boolean;
signIn(user: string, pass: string): Promise<void>;
}
const AuthContext = createContext<AuthContextData>({} as AuthContextData)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.