你可以使用useState Hook来实现
The useState basically, is a feature which helps us preserve the values of variables even after multiple re-renders.
它充当本地状态管理工具,用于在组件呈现或重新呈现后存储值。
除此之外,你还可以通过改变状态变量的值来触发它来更新UI。
const [show,setShow] = useState(true)
这里我们解构了useState发送的值,第一个是变量,通过它我们可以得到值,第二个是一个函数,通过它我们可以更新状态变量的值。
所以,在你的情况下-
import React, {useState} from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
const [show,setShow] = useState(true)
return (
<View style={styles.container}>
{show && <Text style={styles.paragraph}>
Showing and Hiding using useState
</Text>}
<Button
title="Press me"
onPress={() => {setShow(!show)}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
在本例中,在Button press上,我们将状态变量从true切换为false。
您可以使用布尔条件显示或隐藏JSX Code,我们在这条语句中就是这样做的。
{show && <Text style={styles.paragraph}>
Showing and Hiding using useState
</Text>}
这是一种将状态用于UI操作的快速而有效的方法。