鍍金池/ 教程/ HTML/ ReactJS props簡(jiǎn)介
ReactJS動(dòng)畫
ReactJS組件狀態(tài)(State)
ReactJS簡(jiǎn)介
ReactJS開發(fā)環(huán)境設(shè)置
ReactJS Refs
ReactJS組件API
ReactJS高階組件
ReactJS組件
ReactJS props簡(jiǎn)介
ReactJS教程
ReactJS組件生命周期
ReactJS鍵(Key)
ReactJS事件
ReactJS最佳實(shí)踐
ReactJS props驗(yàn)證
ReactJS表單
ReactJS JSX
ReactJS路由器
ReactJS通量概念

ReactJS props簡(jiǎn)介

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

使用props

當(dāng)我們?cè)诮M件中需要不可變的數(shù)據(jù)時(shí),可以在main.js中添加propsreactDOM.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é)果 -

默認(rèn)props

我們也可以直接在組件構(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'));

輸出和以前一樣 -

State 和 Props

以下示例顯示如何在應(yīng)用程序中組合StateProps。 在父組件中設(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é)果會(huì)和前面兩個(gè)例子一樣,唯一不同的是我們數(shù)據(jù)的來源,現(xiàn)在來自state。 當(dāng)想更新它時(shí),只需要更新狀態(tài),所有的子組件都會(huì)被更新。 更多關(guān)于這個(gè)在事件章節(jié)。