BÀI 14 - CẬP NHẬT TRẠNG THÁI - STATE TRONG REACT NATIVE

Video bài học

  • State là một phương thức cập nhật trạng thái, nó sẽ nằm trong màn hình và chờ thay đổi để cập nhật lại giá trị được gán.

  • Đầu tiên, khai báo state trong constructor() sau đó trong render() tạo 2 nút tăng giảm là đã tạo được một chương trình tăng giảm số bằng button

constructor(props) {

super(props);

this.state = {

soDemo: 264

}

}

eventButtonTang() {

this.setState({

soDemo:this.state.soDemo + 1

});

}

eventButtonGiam() {

this.setState({

soDemo:this.state.soDemo - 1

});

}

render() {

return (

<View>

<Text style={styles.sodemo}>{this.state.soDemo}</Text>

</View>

<View style={styles.viewButtonTangGiam}>

<TouchableOpacity onPress={()=>{this.eventButtonGiam()}}>

<View style={[styles.viewButton, styles.viewButtonGiam]}>

<Text style={{color: 'white'}}>Giảm</Text>

</View>

</TouchableOpacity>

<TouchableOpacity onPress={()=>{this.eventButtonTang()}}>

<View style={[styles.viewButton, styles.viewButtonTang]}>

<Text style={{color: 'white'}}>Tăng</Text>

</View>

</TouchableOpacity>

</View>

}

}