React 之常用組件類型

無狀態組件

主要用於內部沒有狀態更新操作的組件。 同構props進行基本的數據渲染或常量展示。 該類組件職責單一,有利於組件的高複用。

const PureComponent = (props) => (
    <div>
       {
           props.list.map((txt, index) => {
               return <li key={index}>{txt}</li>
           })
       }
    </div>
)


// 使用:
class ParentComponent extends Component {
   .....
   render(){
       <PureComponent  list={this.state.list} />
   }
}

有狀態組件

該類型組件可在constructor 中自定義初始狀態, 並擁有完整的生命週期鉤子。 可以執行一些較爲負責的邏輯處理及交互展示。

class StatefulComponent extends Component {

    constructor(props) {
        super(props);
        this.state = {
            //定義狀態
        }
    }

    componentWillMount() {
        //do something
    }

    componentDidMount() {
        //do something
    }
    ... //其他生命週期

    render() {
        return (
            //render
        );
    }
}

容器組件

在實際開發中容器組件可以用來作爲數據請求加工的地方。 爲了使組件的職責更單一,降低組件耦合度, 引入容器組件的概念。(React Redux 的connect() 等都有用到這種組件方式)

      const ProductListComtainer = React.createClass({
          getInitialState(){
              return {
                 pList: [ ]
              }
          },
         componentDidMount() {
         var _this = this;
         axios.get('/api/productList').then((response) =>{
            _this.setState({pList: response.data});
         });
        },
         render(){
            return (<ProductListComtainer pList={pList}></ProductListComtainer>)
         }
      })

高階組件

該類組件組要用在中大型項目中,對複雜的需求,交互情況往往可以利用高階組件寫出更強複用性的組件。其本質是接收一個組件並返回一個新組件(實質是返回組件的函數)。


const HigherOrderComponent = (WrappedComponent) => {
  return class WrapperComponent extends Component {
    render() {
      //do something with WrappedComponent
    }
  }
}

高階組件在原組件的基礎上,可以增加功能,屬性和行爲。通常的開發中我們希望組件儘量純淨或業務單一。 但通常部分組件需要增加一些輔助功能: 打印日誌,獲取數據或校驗等, 這些公共代碼會被重複寫多遍。所以,可以抽象出一個高階組件,用於給基礎組件增加這些功能。

Render Callback 組件

該類型組件在組件中使用渲染回調方式, 將組件中的渲染邏輯委託給其子組件。

import { Component } from "react";

class RenderCallbackCmp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      msg: "hello"
    };
  }

  render() {
    return this.props.children(this.state.msg);
  }
}

const ParentComponent = () =>
  (<RenderCallbackCmp>
    //  <p>{多個子節點時,返回Array}</p>
    //  <p>{多個子節點時,返回Array}</p>
    {msg =>
      //use the msg  返回Object 類型
      <div>
        {msg}
      </div>}
  </RenderCallbackCmp>);

關於this.props.children 值有三種情況: 如果沒有子節點,值爲: undefined; 如果有一個子節點, 值爲:Object; 如果有多個子節點, 值爲: Array。
通過使用React提供的 React.Children來處理this.props.children可以避免返回值類型不一的情況。
如:

..............
   return (
       React.Children.map(this.props.children, (child)=>{
           return <li>{child}</li>
       })
   )
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章