溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

React中高階組件如何使用

發(fā)布時(shí)間:2020-11-10 11:18:39 來(lái)源:億速云 閱讀:161 作者:小新 欄目:web開(kāi)發(fā)

小編給大家分享一下React中高階組件如何使用,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

Higher-Order Components

  • HOC 不是React的標(biāo)準(zhǔn)API。

  • HOC 是一個(gè)函數(shù)。

  • HOC 返回一個(gè)Component

示例:

const EnhancedComponent = higherOrderComponent(WrappedComponent);

使用場(chǎng)景

代碼復(fù)用

類(lèi)似React 0.15版本之前的mixin。

多個(gè)組件同用一段代碼,或者同樣的方法時(shí),可以使用HOC。

示例:

import React, { PureComponent } from 'react';

const Common = (WrapComponent) => {
  return (
    <div>
      <h2>Title</h2>
      <WrapComponent />
    </div>
  );
};

const Header = () => <div>Header</div>;
const Footer = () => <div>Footer</div>;

export default class extends PureComponent {
  render() {
    return (
      <div>
        <div>
          <p>Header Component</p>
          {Common(Header)}
        </div>
        <hr />
        <div>
          <p>Footer Component</p>
          {Common(Footer)}
        </div>
      </div>
    );
  }
}

在線(xiàn)示例

抽象state和更改props

可以通過(guò)WrappedComponent包裹的組件公共state抽象出來(lái)。

可以通過(guò)WrappedComponent包裹的組件傳遞修改、添加等的props.

示例:

const HOComp = (WrappedComponent) => {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {name: ''};
    }

    componentDidMount() {
      this.setState({name: WrappedComponent.displayName || WrappedComponent.name || 'Component';});
    }

    return <WrappedComponent name={this.state.name} {...this.props}/>
  }
}

渲然劫持

條件渲然。根據(jù)props或者state條件返回在渲然的內(nèi)容。

示例:

const HOComp = (WrappedComponent) => {
  return class Enhancer extends WrappedComponent {
    render() {
      if (this.props.loggedIn) {
        return super.render()
      } else {
        return null
      }
    }
  }
}

反向繼承

返回的高階組件類(lèi)(Enhancer)繼承了 WrappedComponent。

示例:

const EnchanceComponent = (WrappedCompopnent) => {
  return class extends WrappedCompopnent {
    constructor(props) {
      super(props);
      this.state = { error: '' };
    }
    componentDidMount() {
      /*do something*/
      super.componentDidMount();
    }
    render() {
      if (this.state.error) {
        return <p>{this.state.error}</p>;
      } else {
        return super.render();
      }
    }
  }
};

看完了這篇文章,相信你對(duì)React中高階組件如何使用有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI