ReactJS 道具(Props)

狀態(tài)和道具之間的主要區(qū)別props是不可變的。這就是為什么容器組件應(yīng)定義可以更新和更改的狀態(tài),而子組件應(yīng)僅使用prop從狀態(tài)傳遞數(shù)據(jù)的原因。

使用道具

當(dāng)我們需要在組件中使用不可變數(shù)據(jù)時,我們可以在main.js中的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>
      );
   }
}

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é)果。

反應(yīng)道具示例

默認(rèn)道具

您還可以直接在組件構(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)道具示例

狀態(tài)與道具

以下示例顯示了如何state在應(yīng)用中進(jìn)行合并和支持。我們在父組件中設(shè)置狀態(tài),然后使用props將其傳遞到組件樹中。在render函數(shù)內(nèi)部,我們正在設(shè)置headerPropcontentProp在子組件中使用。

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é)果將再次與前兩個示例相同,唯一不同的是我們的數(shù)據(jù)源,該數(shù)據(jù)源最初來自state。當(dāng)我們想要更新它時,我們只需要更新狀態(tài),所有子組件都將被更新。

反應(yīng)道具示例

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清