State là nơi chứa dữ liệu của component. Nên giữ state đơn giản nhất có thể và giảm thiểu số component có state (stateful). Nếu nhiều component cần dữ liệu chung, hãy tạo một container component cha chứa state cho tất cả.
Ví dụ 1: Button chuyển đổi ON/OFF
Khởi tạo state trong constructor:
constructor(props) {
super(props);
this.state = { isToggle: true };
}
Tiêu đề button dựa trên isToggle: true -> ON, false -> OFF. Khi nhấn button, onPress gọi setState đảo giá trị:
onPress={() => {
this.setState({ isToggle: !this.state.isToggle });
}}
Mã hoàn chỉnh App.js:
import React, { Component } from "react";
import { Text, View, Button, Alert } from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = { isToggle: true };
}
render(props) {
return (
);
}
}
export default App;
Kết quả
Button chuyển đổi ON/OFF khi nhấn.

Ví dụ 2: Thay đổi text khi nhấn
State ban đầu:
constructor(props) {
super(props);
this.state = { myState: 'Welcome to Tutorialspoint' };
}
Hiển thị trong Text, có onPress gọi changeState:
{this.state.myState}
Hàm cập nhật state:
changeState = () => this.setState({myState: 'Hello World'})
Mã hoàn chỉnh:
import React, { Component } from "react";
import { Text, View, Button, Alert } from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = { myState: 'Welcome to Tutorialspoint' };
}
changeState = () => this.setState({myState: 'Hello World'})
render(props) {
return (
{this.state.myState}
);
}
}
export default App;
Kết quả
