Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 高阶组件 #23

Open
lznbuild opened this issue Jun 14, 2020 · 0 comments
Open

React 高阶组件 #23

lznbuild opened this issue Jun 14, 2020 · 0 comments

Comments

@lznbuild
Copy link
Owner

高阶组件类似于高阶函数,它接受React组件作为输入,输出一个新的React组件。让代码具有复用性,逻辑性,抽象特性。

高阶组件有两种方式:

  • 属性代理

  • 反向继承

属性代理

  • 属性代理方式实现的高阶组件和原组件的生命周期关系完全是React父子组件的生命周期关系

  • 可以操作或者添加新的props

  • 用其他元素包裹 WrappedComponent

  • 通过 Refs 访问到组件实例

// 子组件
  componentDidMount() {
    console.log(this.inputElement ,'child ref') // 可以在子组件中获取对应dom元素 
  }
  render() {
    return (
      <div 
        ref={el => {
          if (this.props.inputRef) {
            this.props.inputRef(el); // 调用父组件传入的ref回调函数
          }
          this.inputElement = el;
        }}
      >
        12111
      </div>

    )
  }
// 高阶组件
 componentDidMount() {
    console.log(this.inputElement, 'wrap ref'); // 可以在高阶组件中获取dom元素 
  }
  render(){
    return <WrappedComponent {...this.props} {...newProps} inputRef={(el)=>{this.inputElement = el}}/>
  }

反向继承

  • 允许高阶组件通过 this 访问到原组件,所以可以直接读取和操作原组件的 state/ref/生命周期方法

  • 可以通过 super.render() 方法获取到传入组件实例的 render 结果,所以可对传入组件进行渲染劫持(最大特点),包括劫持原组件生命周期方法

const MyContainer = (WrappedComponent) =>
  class extends WrappedComponent {
    render() {
      return super.render();
    }
  }

https://zhuanlan.zhihu.com/p/24776678

https://juejin.im/post/5e169204e51d454112714580?utm_source=gold_browser_extension

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant