加入收藏 | 设为首页 | 会员中心 | 我要投稿 晋中站长网 (https://www.0354zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

【React深入】从Mixin到HOC再到Hook

发布时间:2019-04-12 04:39:12 所属栏目:优化 来源:ConardLi
导读:导读 前端发展速度非常之快,页面和组件变得越来越复杂,如何更好的实现状态逻辑复用一直都是应用程序中重要的一部分,这直接关系着应用程序的质量以及维护的难易程度。 本文介绍了React采用的三种实现状态逻辑复用的技术,并分析了他们的实现原理、使用方

如果原组件有非常多的静态属性,这个过程是非常痛苦的,而且你需要去了解需要增强的所有组件的静态属性是什么,我们可以使用hoist-non-react-statics来帮助我们解决这个问题,它可以自动帮我们拷贝所有非React的静态方法,使用方式如下:

  1. import hoistNonReactStatic from 'hoist-non-react-statics';  
  2. function proxyHOC(WrappedComponent) {  
  3.   class HOCComponent extends Component {  
  4.     render() {  
  5.       return <WrappedComponent {...this.props} />;  
  6.     }  
  7.   }  
  8.   hoistNonReactStatic(HOCComponent,WrappedComponent);  
  9.   return HOCComponent;  

告诫—传递refs

使用高阶组件后,获取到的ref实际上是最外层的容器组件,而非原组件,但是很多情况下我们需要用到原组件的ref。

高阶组件并不能像透传props那样将refs透传,我们可以用一个回调函数来完成ref的传递:

  1. function hoc(WrappedComponent) {  
  2.   return class extends Component {  
  3.     getWrappedRef = () => this.wrappedRef;  
  4.     render() {  
  5.       return <WrappedComponent ref={ref => { this.wrappedRef = ref }} {...this.props} />;  
  6.     }  
  7.   }  
  8. }  
  9. @hoc  
  10. class Input extends Component {  
  11.   render() { return <input></input> }  
  12. }  
  13. class App extends Component {  
  14.   render() {  
  15.     return (  
  16.       <Input ref={ref => { this.inpitRef = ref.getWrappedRef() }} ></Input>  
  17.     );  
  18.   }  

(编辑:晋中站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读