在 React 中,props 和 state 是兩個(gè)核心概念,用于管理組件的數(shù)據(jù)和狀態(tài)。
Props(屬性):
- props 是組件之間傳遞數(shù)據(jù)的一種方式,用于從父組件向子組件傳遞數(shù)據(jù)。
- props 是只讀的,即父組件傳遞給子組件的數(shù)據(jù)在子組件中不能被修改。
- props 是在組件的聲明中定義,通過(guò)組件的屬性傳遞給子組件。
- props 的值由父組件決定,子組件無(wú)法直接改變它的值。
- 當(dāng)父組件的 props 發(fā)生變化時(shí),子組件會(huì)重新渲染。
例如:
function ParentComponent() {
const name = "John";
return <ChildComponent name={name} />;
}
function ChildComponent(props) {
return <p>Hello, {props.name}!</p>;
}
在上述示例中,ParentComponent 將名為 "John" 的值通過(guò) name 屬性傳遞給了 ChildComponent,ChildComponent 使用 props.name 來(lái)顯示該值。
State(狀態(tài)):
- state 是組件內(nèi)部的數(shù)據(jù),用于管理組件的狀態(tài)和變化。
- state 是可變的,組件可以通過(guò) setState 方法來(lái)更新和修改 state。
- state 是在組件的構(gòu)造函數(shù)中初始化的,通常被定義為組件的類屬性。
- state 的值可以由組件自身內(nèi)部改變,通過(guò)調(diào)用 setState 方法觸發(fā)組件的重新渲染。
- 當(dāng)組件的 state 發(fā)生變化時(shí),組件會(huì)重新渲染。
例如:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.handleClick()}>Increment</button>
</div>
);
}
}
以上的示例中,MyComponent
組件內(nèi)部有一個(gè)count
的狀態(tài),通過(guò) this.state.count
來(lái)訪問(wèn)它。當(dāng)按鈕點(diǎn)擊時(shí),handleClick 方法會(huì)調(diào)用setState
方法來(lái)更新 count
的值,并觸發(fā)組件的重新渲染。
總結(jié):
- props 是父組件傳遞給子組件的數(shù)據(jù),是只讀的,子組件無(wú)法直接修改它。
- state 是組件內(nèi)部的數(shù)據(jù),是可變的,組件可以通過(guò) setState 方法來(lái)修改它。
- props 用于組件之間的數(shù)據(jù)傳遞,而 state 用于管理組件自身的狀態(tài)和變化。