gpt4 book ai didi

javascript - 如何在React Native其他函数中使用useState

转载 作者:行者123 更新时间:2023-12-02 02:04:30 25 4
gpt4 key购买 nike

我有一个关于 React Native 的问题。我想在此处的文本输入中写入用户名

function logIn({ navigation }) {

const [username, setUsername] = useState('');

return (
<View style={{ backgroundColor: "white"}} >
<View>
<TextInput style={styles.input} placeholder='username' placeholderTextColor='white' textAlign='center' onChangeText={(val) => setUsername(val)} />
</View>
<View>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
</View>
</View>
);
}

然后我想看到我在这个屏幕上写的用户名。当然这不起作用,因为它显示无法找到变量用户名,所以有办法解决这个问题吗?

function HomeScreen({ navigation }) {
return(
<View style={{ flex:1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Welcome {username}</Text>
</View>
);
}

最佳答案

您需要以一种可供需要它的组件访问的方式构建您的状态。 React 希望您在树中比需要它的组件“更高”的组件中拥有状态,您可以查看 https://reactjs.org/docs/lifting-state-up.html为此。

否则,您可以使用 Context API 或 Redux 等“全局”存储。

登录的用户数据是 Context 或 Redux 等的良好候选者,这样您就可以在 Context/Redux 内的应用程序的任何部分访问用户名之类的数据提供登录数据(或您可能拥有的任何其他全局数据)的提供商

关于javascript - 如何在React Native其他函数中使用useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68619831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com