State คือที่มาของข้อมูล เราควรพยายามทำให้ state เรียบง่ายที่สุดและลดจำนวน stateful components ให้น้อยที่สุด หากมีคอมโพเนนท์ 10 ตัวที่ต้องการข้อมูลจาก state ควรสร้าง container component เดียวที่จะเก็บ state ให้ทั้งหมด
ตัวอย่าง 1
เปลี่ยน title ปุ่มเป็น ON/OFF เมื่อผู้ใช้กดปุ่ม
State เริ่มต้นใน constructor:
constructor(props) {
super(props);
this.state = { isToggle: true };
}
isToggle เป็นค่า boolean ของ state title ของปุ่มถูกกำหนดโดย isToggle หาก true title คือ ON มิฉะนั้น OFF
เมื่อกดปุ่ม onPress จะเรียก setState อัปเดต isToggle:
onPress={() => {
this.setState({ isToggle: !this.state.isToggle });
}}
เมื่อผู้ใช้กดปุ่ม onPress จะถูกเรียก และ setState จะเปลี่ยน state ของ isToggle
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;
ผลลัพธ์
ปุ่มจะสลับ ON/OFF เมื่อผู้ใช้กด

ตัวอย่าง 2
เปลี่ยนข้อความเมื่อผู้ใช้คลิกที่ข้อความ
State แสดงใน constructor:
constructor(props) {
super(props);
this.state = { myState: 'Welcome to Tutorialspoint' };
}
State myState แสดงใน Text component:
{this.state.myState}
เมื่อผู้ใช้แตะ/กดข้อความ onPress จะยิงและเรียก this.changeState ที่เปลี่ยนข้อความโดยอัปเดต state myState:
changeState = () => this.setState({myState: 'Hello World'})
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;
ผลลัพธ์
