รัฐเป็นที่ที่ข้อมูลมาจาก เราควรพยายามทำให้สถานะของเราเรียบง่ายที่สุดเท่าที่จะทำได้ และลดจำนวนองค์ประกอบการเก็บสถานะให้น้อยที่สุด ตัวอย่างเช่น หากเรามีส่วนประกอบ 10 รายการที่ต้องการข้อมูลจากสถานะ เราควรสร้างส่วนประกอบคอนเทนเนอร์หนึ่งรายการที่จะคงสถานะไว้สำหรับส่วนประกอบทั้งหมด
ตัวอย่างที่ 1
ชื่อปุ่มเปลี่ยนเป็นเปิด/ปิดเมื่อผู้ใช้กดปุ่ม
สถานะเริ่มต้นภายในตัวสร้างดังแสดงด้านล่าง -
constructor(props) {
super(props);
this.state = { isToggle: true };
} isToggle คือค่าบูลีนที่กำหนดให้กับรัฐ ชื่อของปุ่มจะขึ้นอยู่กับคุณสมบัติ isToggle หากค่าเป็นจริง ชื่อของปุ่มจะเป็น ON มิฉะนั้น OFF
เมื่อกดปุ่ม วิธีการ onpress จะถูกเรียกซึ่งเรียก setState ที่อัพเดตค่า isToggle ดังที่แสดงด้านล่าง -
onPress={() => {
this.setState({ isToggle: !this.state.isToggle });
}} เมื่อผู้ใช้คลิกที่ปุ่มเหตุการณ์ onPress จะถูกเรียกและ setState จะเปลี่ยนสถานะของคุณสมบัติ 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 (
<View style={{flex :1, justifyContent: 'center', margin: 15 }}>
<Button
onPress={() => {
this.setState({ isToggle: !this.state.isToggle });
}}
title={
this.state.isToggle ? 'ON' : "OFF"
}
color="green"
/>
</View>
);
}
}
export default App; ผลลัพธ์
ปุ่มจะสลับเมื่อผู้ใช้กดปุ่ม

ตัวอย่างที่ 2
เปลี่ยนข้อความเมื่อผู้ใช้คลิก
ในตัวอย่างด้านล่าง สถานะจะแสดงภายในตัวสร้างดังนี้ −
constructor(props) {
super(props);
this.state = { myState: 'Welcome to Tutorialspoint' };
} สถานะ myState จะแสดงอยู่ในองค์ประกอบข้อความดังนี้ -
<Text onPress={this.changeState} style={{color:'red', fontSize:25}}>{this.state.myState} </Text> เมื่อผู้ใช้สัมผัสหรือกดข้อความเหตุการณ์ onPress จะถูกไล่ออกและเรียกเมธอด this.changeState ที่เปลี่ยนข้อความโดยอัปเดตสถานะ 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 (
<View style={{flex :1, justifyContent: 'center', margin: 15 }}>
<View>
<Text onPress={this.changeState} style={{color:'red', fontSize:25}}> {this.state.myState} </Text>
</View>
</View>
);
}
}
export default App; ผลลัพธ์
