React Native 状态管理:函数组件 vs 类组件
在React Native中,状态(state
)的管理可以通过函数组件使用useState
和useEffect
钩子来实现,也可以通过类组件的传统方式来处理。以下分别展示了这两种方式的具体实现。
使用函数组件与Hooks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const Index = () => { const [statusBarColor, setStatusBarColor] = useState('green'); useEffect(() => { StatusBar.setBackgroundColor(statusBarColor); }, [statusBarColor]); const toggleStatusBarColor = () => { const newColor = statusBarColor === 'green' ? 'red' : 'green'; setStatusBarColor(newColor); }; return ( <View style={styles.container}> <Switch trackColor={{ false: 'gray', true: 'green' }} thumbColor="blue" onValueChange={toggleStatusBarColor} value={statusBarColor==='green'} /> </View> ); }
|
使用类组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| export default class Index extends Component { constructor(props) { super(props); this.state = { statusBarColor: 'green', switchValue: true }; }
componentDidUpdate(prevProps, prevState) { if (prevState.statusBarColor !== this.state.statusBarColor) { StatusBar.setBackgroundColor(this.state.statusBarColor); } } toggleStatusBarColor = () => { const newColor = this.state.statusBarColor === 'green' ? 'red' : 'green'; this.setState({ statusBarColor: newColor, switchValue: !this.state.switchValue }); }; render() { return ( <View style={styles.container}> <Switch trackColor={{ false: 'gray', true: 'green' }} thumbColor="blue" onValueChange={this.toggleStatusBarColor} value={this.state.switchValue} /> </View> ); } }
|