狀態(tài)和道具之間的主要區(qū)別props是不可變的。這就是為什么容器組件應(yīng)定義可以更新和更改的狀態(tài),而子組件應(yīng)僅使用prop從狀態(tài)傳遞數(shù)據(jù)的原因。
當(dāng)我們需要在組件中使用不可變數(shù)據(jù)時,我們可以在main.js中的reactDOM.render()函數(shù)中添加道具,并在組件中使用它。
import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>{this.props.headerProp}</h1> <h2>{this.props.contentProp}</h2> </div> ); } }
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 ()元素中。
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;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app'));
輸出與以前相同。
以下示例顯示了如何state在應(yīng)用中進(jìn)行合并和支持。我們在父組件中設(shè)置狀態(tài),然后使用props將其傳遞到組件樹中。在render函數(shù)內(nèi)部,我們正在設(shè)置headerProp并contentProp在子組件中使用。
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;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app'));
結(jié)果將再次與前兩個示例相同,唯一不同的是我們的數(shù)據(jù)源,該數(shù)據(jù)源最初來自state。當(dāng)我們想要更新它時,我們只需要更新狀態(tài),所有子組件都將被更新。