setState
要在應用程式中更改檢視,可以使用 setState
- 這將重新呈現元件及其任何子元件。setState 在新狀態和先前狀態之間執行淺合併,並觸發重新呈現元件。
setState
接受鍵值物件或返回鍵值物件的函式
鍵值物件
this.setState({myKey: 'myValue'});
功能
使用函式對於根據現有狀態或道具更新值非常有用。
this.setState((previousState, currentProps) => {
return {
myInteger: previousState.myInteger+1
}
})
你還可以將可選回撥傳遞給 setState
,當元件使用新狀態重新呈現時將觸發該回撥。
this.setState({myKey: 'myValue'}, () => {
// Component has re-rendered... do something amazing!
));
完整的例子
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default class MyParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
myInteger: 0
}
}
getRandomInteger() {
const randomInt = Math.floor(Math.random()*100);
this.setState({
myInteger: randomInt
});
}
incrementInteger() {
this.setState((previousState, currentProps) => {
return {
myInteger: previousState.myInteger+1
}
});
}
render() {
return <View style={styles.container}>
<Text>Parent Component Integer: {this.state.myInteger}</Text>
<MyChildComponent myInteger={this.state.myInteger} />
<Button label="Get Random Integer" onPress={this.getRandomInteger.bind(this)} />
<Button label="Increment Integer" onPress={this.incrementInteger.bind(this)} />
</View>
}
}
export default class MyChildComponent extends Component {
constructor(props) {
super(props);
}
render() {
// this will get updated when "MyParentComponent" state changes
return <View>
<Text>Child Component Integer: {this.props.myInteger}</Text>
</View>
}
}
export default class Button extends Component {
constructor(props) {
super(props);
}
render() {
return <TouchableOpacity onPress={this.props.onPress}>
<View style={styles.button}>
<Text style={styles.buttonText}>{this.props.label}</Text>
</View>
</TouchableOpacity>
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
button: {
backgroundColor: '#444',
padding: 10,
marginTop: 10
},
buttonText: {
color: '#fff'
}
});
AppRegistry.registerComponent('MyApp', () => MyParentComponent);