狀態是數據的來源。我們應該始終嘗試使我們的狀態盡可能簡單,并盡量減少有狀態組件的數量。例如,如果我們有 10 個需要狀態數據的組件,我們應該創建一個容器組件來保存所有這些組件的狀態。
示例 1
當用戶按下按鈕時,按鈕標題更改為ON/OFF。
狀態在構造函數內初始化,如下所示 –
constructor(props) {
super(props);
this.state = { isToggle: true };
}
登錄后復制
isToggle 是賦予狀態的布爾值。按鈕的標題是根據 isToggle 屬性決定的。如果值為 true,則按鈕的標題為 ON,否則為 OFF。
當按下按鈕時,將調用 onpress 方法,該方法會調用更新 isToggle 值的 setState,如下所示 –
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 組件內,如下 –
<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;
登錄后復制
輸出
以上就是React Native 中的狀態是什么?的詳細內容,更多請關注www.92cms.cn其它相關文章!






