react

react反向继承注意点

2019-03-13  本文已影响0人  你的时间非常值钱

react高阶组件有一种实现方式叫反向继承(Inheritance Inversion),简称II

案例.png
场景:需要开发一堆有相同特性的按钮组件,相同特性包括内容初始值为零,每次点击后自增1,使用反向继承看看

在线代码地址

class Button1 extends Component {
  componentDidMount() {
    console.log("didMount1");
  }
  render() {
    console.log("render1");
    return <button />;
  }
}
// 高阶组件函数
const Hoc = WrappedComponent => {
  return class extends WrappedComponent {
    state = {
      num: 0
    };
    componentDidMount() {
      console.log("didMountHoc");
    }
    handleClick = () => {
      this.setState({
        num: this.state.num + 1
      });
    };
    render() {
      console.log("renderHoc");
      // 核心代码
      let renderTree = super.render();
      let newProps = {
        ...renderTree.props,
        onClick: this.handleClick
      };
      const newRenderTree = React.cloneElement(
        renderTree,
        newProps,
        this.state.num
      );
      return newRenderTree;
    }
  };
};

反向继承两大作用,一是渲染劫持,二是操作state

看看控制台,发现Button1(被包裹组件)的componentDidMount没触发,发现被Hoc的相同方法覆盖了


生命周期被覆盖.png

处理方法就是不出现同名方法(生命周期),或者手动super[function]调用被包裹组件的方法


手动覆盖.png

注意state,props也会覆盖的

state被覆盖.png
上一篇 下一篇

猜你喜欢

热点阅读