props
和state
的主要區(qū)別是props
是不變的。 這就是為什么容器組件應(yīng)該定義可以更新和更改的狀態(tài),而子組件只應(yīng)該使用props
來傳遞狀態(tài)數(shù)據(jù)。
當(dāng)我們?cè)诮M件中需要不可變的數(shù)據(jù)時(shí),可以在main.js
中添加props
到reactDOM.render()
函數(shù)中,并在組件中使用它。
文件:App.jsx -
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
export default App;
文件:main.js -
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App headerProp = "Header from props..." contentProp = "Content
from props..."/>, document.getElementById('app'));
export default App;
這將產(chǎn)生以下結(jié)果 -
我們也可以直接在組件構(gòu)造函數(shù)中設(shè)置默認(rèn)屬性值,而不是將其添加到reactDom.render()
元素。
文件:App.jsx -
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
App.defaultProps = {
headerProp: "Header from props...",
contentProp:"Content from props..."
}
export default App;
文件:main.js -
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
輸出和以前一樣 -
以下示例顯示如何在應(yīng)用程序中組合State
和 Props
。 在父組件中設(shè)置狀態(tài)并使用Props
將其傳遞給組件樹。 在render
函數(shù)內(nèi)部,設(shè)置了在子組件中使用的headerProp
和contentProp
。
文件:App.jsx -
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Header from props...",
content: "Content from props..."
}
}
render() {
return (
<div>
<Header headerProp = {this.state.header}/>
<Content contentProp = {this.state.content}/>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
export default App;
文件:main.js -
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
結(jié)果會(huì)和前面兩個(gè)例子一樣,唯一不同的是我們數(shù)據(jù)的來源,現(xiàn)在來自state
。 當(dāng)想更新它時(shí),只需要更新狀態(tài),所有的子組件都會(huì)被更新。 更多關(guān)于這個(gè)在事件章節(jié)。