什么是State
props是不可改變,只讀的。為了實現交互,就需要用到組件的state。我們將組件看為狀態機,UI是各種各樣的狀態,並在各種各樣的狀態之間可以切換,只需要改變組件的state,就會重新渲染UI。
state是組件私有的,是沒有辦法通過其他組件傳遞過來的。
state的兩種聲明方式
import React from 'react';
import {Text, View} from "react-native";
export default class StateTest extends React.Component {
/**
* 方式二
* @type {{size: number}}
*/
state = {
size: 100,
};
constructor() {
super();
/**
* 方式一
*/
// this.state = {
// size: 80,
// };
}
render() {
return (
<View>
<Text style={{fontSize: 20, color: 'red'}}>{this.state.size}</Text>
</View>
);
}
}
設置State
this.setState({
size: this.state.size - 10
})