React組件的數據分為兩種,prop和state,無論prop或者state的改變,都可能引發組件的重新渲染,那么,設計一個組件的時候,什么時候選擇用prop什么時候用state呢?原則很簡單,prop是組件的對外接口,state是組件的內部狀態,對外用prop,對內用state。
React的prop
prop是property的簡寫,是從外部傳遞給組件的數據,一個React組件通過定義自己能夠接受的prop就定義了自己的對外公共接口。
每個React組件都是獨立存在的模塊,組件之外的一切都是外部世界,外部世界就是通過prop來和組件對話的。
讀取prop
class Children1 extends React.Component {
render() {
return (
<div>{this.props.a1}</div> //這里props.a1就是Children1相對于父組件的接口
)
}
}
給prop賦值,并接受父組件傳的參數
class Rongqi extends React.Component {
render() {
return (
<div>
<h1>{this.state.h1}</h1>
<Children1 a1={'任何數據'} /> //Children1組件調用,a1接受父親傳的參數
</div>
)
}
}
React的state
驅動組件渲染的過程除了prop,還有state,state代表組件的內部狀態。由于React不能修改傳入的prop,所以需要記錄自身數據的變化,就要使用state。
初始化state
constructor(props) {
super(props);
this.state = {
h1: '父親數據111',
a1: '兒子數據111',
a2: '兒子數據222'
}
}
讀取和更新state
改變組件state必須使用this.setState函數,不能直接去修改this.state。
class Rongqi extends React.Component {
constructor(props) {
super(props);
this.state = {
h1: '父親數據111',
a1: '兒子數據111',
a2: '兒子數據222'
}
}
render() {
return (
<div>
<h1>{this.state.h1}</h1> //子組件Children2向父組件傳數據
<Children1 a1={this.state.a1} /> //父組件向子組件Children1傳數據
<Children2 a2={this.state.a2} setstate={this.setState.bind(this)} />
</div>
)
}
}
class Children1 extends React.Component {
render() {
return (
<div>{this.props.a1}</div>
)
}
}
class Children2 extends React.Component {
constructor(props) {
super(props);
this.state = {
a2: '2222兒子的數據'
}
}
render() {
return (
<div onClick={() => {
this.props.setstate({ h1: '我是兒子的數據' })
}}>{this.props.a2}</div>
)
}
}
prop和state的對比
- prop用于定義外部接口,state用于記錄內部狀態;
- prop的賦值在外部世界使用組件時,state的賦值在組件內部;
- 組件不應該改變prop的值,state存在的目的就是讓組件來改變的。
組件的state就相當于組件的記憶,其存在意義就是被修改,每一次通過this.setState就改變了組件的狀態,然后通過渲染過程把這種變化體現出來。