天天看點

初識React(7):高階元件

什麼是高階元件

高階元件,聽着好像很高大尚,但是其實高階元件就是一個函數的參數是元件,傳回的是一個新的元件。那麼,高階元件有什麼好處呢,高階元件可以減少代碼備援,把共有的代碼提取出來,下面有個例子說明下:

import React from 'react'

function NewHigher(ComponentTest){
  class NewComponent extends React.Component {
    constructor() {
      super();
      this.state = {
          content: '我是内容'
      }
   }

    render() {
      return (
        <div>
           <h2>高階元件</h2>
           <ComponentTest content={this.state.content}/>
        </div>
      )
    }
  }

  return NewComponent

}

export default NewHigher;
           

NewHigher傳回的就是高階元件

import React from 'react';
import NewHigher from './higherComponent.js'

class Test extends React.Component {
  render() {
    return (
      <div>
        <div>測試元件</div>
        <div>{this.props.content}</div>
      </div>
    )
  }
}

export default NewHigher(Test);
           

高階元件可以這麼了解吧,就是給現有元件設定一個父級,父級有的東西,現有元件都繼承了,是以我們可以把所有共有的東西放在這個高階元件中。在上面那個例子中,NewHigher就是父級,Test繼承了父級中的所有東西。

繼續閱讀