React 高階組件(8)

高階組件

High Order Component

  1. HOC 是一種高級的設(shè)計模式
  2. HOC 是一個函數(shù),接收一個組件參數(shù),返回一個新組件
  3. 普通組件返回的是 UI,HOC 返回的是一個新組件
  4. HOC 不能修改參數(shù)組件,只能傳入組件所需的 props
  5. HOC 是一個沒有副作用的純函數(shù)
  6. HOC 除了必須填入被包裹的組件參數(shù)外,其他參數(shù)根據(jù)需求增加
  7. HOC 不關(guān)心數(shù)據(jù)如何使用,包裹組件不關(guān)心數(shù)據(jù)從哪里來
  8. HOC 和包裹組件唯一直接的契合點就是 props

HOC 更加關(guān)注邏輯和狀態(tài)的管理,參數(shù)組件的邏輯與狀態(tài)訂閱;
參數(shù)組件基本只需關(guān)注視圖的渲染;

function fetchListData(field) {
  return new Promise((resolve, reject) => {
    resolve({
      data: [
        {
          name: "zs",
          age: 12,
          score: 44,
        },
        {
          name: "ls",
          age: 12,
          score: 44,
        },
        {
          name: "ww",
          age: 12,
          score: 44,
        },
      ],
    });
  });
}

function listHoc(WrapperComponent, fetchListData) {
  return class extends React.Component {
    state = {
      listData: [],
    };
    async componentDidMount() {
      const result = await fetchListData(this.props.field);

      this.setState({
        listData: result.data,
      });
    }

    removeStd(name) {
      this.setState({
        listData: this.state.listData.filter((item) => item.name !== name),
      });
    }

    render() {
      return (
        <WrapperComponent
          data={this.state.listData}
          removeStd={this.removeStd.bind(this)}
        />
      );
    }
  };
}

class StudentList extends React.Component {
  render() {
    return (
      <table border="1">
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Score</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {this.props.data.map((item, index) => (
            <tr>
              <td>{item.name}</td>
              <td>{item.age}</td>
              <td>{item.score}</td>
              <td onClick={() => this.props.removeStd(item.name)}>刪除</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}

const StudentListHoc = listHoc(StudentList, fetchListData);

class App extends React.Component {
  render() {
    return <StudentListHoc field="student" />;
  }
}

ReactDOM.render(<App />, document.querySelector("#app"));
function InputHoc(WrapperComp) {
  // 會導致原組件聲明周期中對應的函數(shù)不會執(zhí)行,相當于重寫
  // 不能這樣修改,可能會導致組件內(nèi)部的邏輯失效
  // WrapperComp.prototype.componentDidUpdate = function () {
  //   console.log("Input Hoc1");
  // };

  class InputComponent extends React.Component {
    state = {
      value: "",
    };
    // 這里和上面的重寫不沖突
    // 可以在這里重寫函數(shù),與原組件內(nèi)部邏輯不沖突,用作對原組件邏輯的擴展
    componentDidUpdate() {
      console.log("Input Hoc2");
    }

    chgInput(e) {
      this.setState({
        value: e.target.value,
      });
    }
    render() {
      const { a, ...props } = this.props;

      return (
        <WrapperComp
          value={this.state.value}
          chgInput={this.chgInput.bind(this)}
          {...props}
        />
      );
    }
  }
  // 可以改變別名
  InputComponent.displayName = "InputHoc";

  return InputComponent;
}

class MyInput extends React.Component {
  componentDidUpdate() {
    console.log("MyInput");
  }

  render() {
    return (
      <div>
        <p>總計:{this.props.b + this.props.c}</p>
        <p>
          <input
            type="text"
            defaultValue={this.props.value}
            onChange={this.props.chgInput}
          />
        </p>
        <p>{this.props.value}</p>
      </div>
    );
  }
}

const MyInputHoc = InputHoc(MyInput);

class App extends React.Component {
  state = {
    a: 1,
    b: 2,
    c: 3,
  };

  render() {
    return <MyInputHoc {...this.state} />;
  }
}
ReactDOM.render(<App />, document.querySelector("#app"));
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 高階組件 HOC 高階組件(HOC)是react中的高級技術(shù),用來重用組件邏輯。但高階組件本身并不是React A...
    編程之上閱讀 809評論 0 2
  • 寫在前面(說點廢話) 作為一個react開發(fā)者,提起高階組價,我想并不陌生,即使是沒聽過,我相信,你毫無察覺的用過...
    喜劇之王愛創(chuàng)作閱讀 4,549評論 0 5
  • 探索Vue高階組件 高階組件(HOC)是 React 生態(tài)系統(tǒng)的常用詞匯,React 中代碼復用的主要方式就是使用...
    君惜丶閱讀 1,060評論 0 2
  • 探索Vue高階組件高階組件(HOC)是 React 生態(tài)系統(tǒng)的常用詞匯,React 中代碼復用的主要方式就是使用高...
    videring閱讀 10,708評論 5 30
  • 高階組件(HOC)是 React 中用于復用組件邏輯的一種高級技巧。HOC 自身不是 React API 的一部分...
    明里人閱讀 735評論 0 1

友情鏈接更多精彩內(nèi)容