wangyuan0108 / fe-qa

知识和笔记,整理分享,以便提升和巩固
https://github.com/wangyuan0108/blog/issues
13 stars 0 forks source link

高阶组件实现中的属性代理和反向继承 #84

Open wangyuan0108 opened 4 years ago

wangyuan0108 commented 4 years ago

就是类似高阶函数的定义,将组件作为参数或者返回一个组件的组件

wangyuan0108 commented 4 years ago

属性代理

import React,{Component} from 'react';

const Seventeen = WrappedComponent =>
  class extends React.Component {
    render() {
      const props = {
        ...this.props,
        name: "这是高阶组件"
      };
      return <WrappedComponent {...props} />;
    }
  };

class WrappedComponent extends React.Component {
  state={
     baseName:'这是基础组件' 
  }
  render() {
    const {baseName} = this.state
    const {name} = this.props
    return <div>
        <div>基础组件值为{baseName}</div>
        <div>通过高阶组件属性代理的得到的值为{name}</div>
    </div>
  }
}

export default Seventeen(WrappedComponent)
wangyuan0108 commented 4 years ago

反向继承

原理就是利用 super 改变改组件的 this 方向,继而就可以在该组件处理容器组件的一些值

  const Seventeen = (WrappedComponent)=>{
    return class extends WrappedComponent {
        componentDidMount() {
            this.setState({baseName:'这是通过反向继承修改后的基础组件名称'})
        }
        render(){
            return super.render();
        }
    }
}

class WrappedComponent extends React.Component {
  state={
     baseName:'这是基础组件' 
  }
  render() {
    const {baseName} = this.state
    return <div>
        <div>基础组件值为{baseName}</div>
    </div>
  }
}

export default Seventeen(WrappedComponent);