跨平台通用的组件。这是一个受控组件,你必须使用onValueChange回调来更新value属性以响应用户的操作。如果不更新value属性,组件只会按一开始给定的value值来渲染且保持不变,看上去就像完全点不动。
import {View, Text, StatusBar, Switch, Platform} from 'react-native'; import {useEffect, useState} from 'react'; function HomeScreen() { const [isEnabled, setIsEnabled] = useState(false); const toggleSwitch = () => setIsEnabled(previousState => !previousState); useEffect(() => { if (Platform.OS === 'android') { alert('Android device detected. '); } else { Alert('iOS device detected. '); } }, []); return ( { flex: 1, justifyContent: 'center', alignItems: 'center', width: '100%', backgroundColor: '#F5FCFF', }}> 开关状态: {isEnabled ? 'On' : 'Off'} toggleSwitch} thumbColor={isEnabled ? '#f5dd4b' : '#f4f3f4'} trackColor={{false: '#c491f7', true: '#81b0ff'}} value={isEnabled} /> 禁用状态: ); } export default HomeScreen;
这样就实现了一个切换功能,展示不同的内容
上一篇:Vue实现当前页面刷新的方法总结
下一篇:(数据结构)散列表笔记