React高阶组件中使用React.forwardRef的技巧

摘要:
ForwardRef之前使用react决不能用于react的高阶组件。最近,它终于问世并被录制。关键点是React中的ref。forwardRef的API必须指向dom元素而不是React组件。

之前使用react.forwardRef始终无法应用于react高阶组件中,最近终于捣鼓出来了,于是记录下来。关键点就是React.forwardRef的API中ref必须指向dom元素而不是React组件。

一、React.forwardRef使用示例

下面就是应用到React组件的错误示例:

constA=React.forwardRef((props,ref)=><B{...props}ref={ref}/>)

这就是我之前经常犯的错误, 这里的ref是无法生效的。

前面提到ref必须指向dom元素,那么正确方法就应用而生:

const  A=React.forwardRef((props,ref)=>(
<divref={ref}>
<B {...props} />
</div>
))

二、React.forwardRef应用到高阶组件中

2.1. withComponent类型的高阶组件【1】

import React from 'react'
import A from './a.jsx'
import PropTypes from 'prop-types';

function withA(Component){
    const ForWardedComponent = React.forwardRef((props, ref) => <div ref={ref}>
               <Component {...props} />
           </div>);
     class MidComponent extends React.Component {
        render() {
            const props = this.props
            return (
                <A {...props}>
                  <ForWardedComponent  ref={props.forwardedRef} {...props}/>
            </A>
            )
        }
    }
    
    //对MidComponent组件属性进行类型经查 
    MidComponent.propTypes = {
        forwardedRef: PropTypes.object,
    }
    return  MidComponent
}
exports.withA=withA

这样,在上述示例的组件A中,A的周期componentDidMount() 调用 this.props.forwardedRef.current ,指向的就是上述示例中ForWardedComponent对应的dom元素。
是B组件对应的dom的父元素,而不是该dom
在a.jsx中某处:

    componentDidMount(){
     console.log(this.props.forwardedRef.current)
    }

最后应用实例:

import React from 'react'
import ReactDOM from  'react-dom'
//假设withA存储于withA.js文件。
import {withA}   from  './withA.js'  
 const B=()=><h2>hello world</h2>
const B2=withA(B)
class App extends React.Component {
      constructor(props) {
        super(props)
        this.forwardedRef=React.creactRef()        
        }
        
        render() {
           return  <div>
               <B2  forwardedRef={this.forwardedRef}/>
           </div>
        }
}

ReactDOM.render(<App/>,document.getElementById('app'))
     

2.2 纯粹的高阶组件(Parent-Child)
【1】中并不是React组件,只是一个React组件为参数的函数,调用以后才成为React组件。那么直接写入一个Parent组件又该如何呢?

import React from 'react'
import A from './a.jsx'
import PropTypes from 'prop-types';

function AasParent(props){
    const ForWardedComponent = React.forwardRef((props, ref) => <div ref={ref}>
               {props.children}
           </div>);
      return (
                <A {...props}>
                  <ForWardedComponent  ref={props.forwardedRef} {...props}/>
            </A>)
}
AasParent.propTypes = {
        forwardedRef: PropTypes.object,
    }
 
module.exports=AasParent

最后应用实例:

import React from 'react'
import ReactDOM from  'react-dom'
//假设AasParent存储于AasParent.jsx文件。注意与【1】中的区别
import AasParent   from  './AasParent.jsx'  
 const B=(props)=><h2>{props.greetings}</h2>

class App extends React.Component {
      constructor(props) {
        super(props)
        this.forwardedRef=React.creactRef()        
        }
        
        render() {
           return  <AasParent forwardedRef={this.forwardedRef}>
               <B2  greetings="你好,Melo"/>
           </AasParent>
        }
}

ReactDOM.render(<App/>,document.getElementById('app'))
     

广州品牌设计公司https://www.houdianzi.comPPT模板下载大全https://redbox.wode007.com

三、总结

1.React.forwardRef的API中ref必须指向dom元素而不是React组件。
2.在【1】的组件A中,A的周期componentDidMount() 调用 this.props.forwardedRef.current ,指向的就是【1】中ForWardedComponent对应的dom元素。是【1】中B组件对应的dom的父dom元素,而不是该dom。

3.codepen实例

免责声明:文章转载自《React高阶组件中使用React.forwardRef的技巧》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇基于角色的访问控制rbac itprobie微信小程序-最新获取用户基本信息方案下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

JavaScript高级程序设计(一):JavaScript简介

一、JavaScript实现   1、一个完整的JavaScript包含三个部分组成:     1)ECMAScript 核心     2)DOM文档对象模型     3)BOM浏览器对象模型   2、文档对象模型(DOM)   文档对象模型是针对XML单经过扩展用户HTML的应用程序编程接口。DOM 把整个页面映射为一个多层节点结构。HTML或XML页面中...

【React】react学习笔记10-兄弟组件间的传值

上一篇博文简述了脚手架的使用,以及在ws中的简单配置,详细的配置方法就不讲了,可能有很多细节,在日常使用中发掘就好。然后是脚手架的项目结构以及之间的联系,这个完全可以自己找出来,再不济就百度一下就好。 今天记录一下组件之间的传值问题,特别是兄弟组件的传值,真的是为难了我好久的一个问题: 要做啥呢?: 方便兄弟组件中传值,我知道的实现方式有两种,一种是使用R...

JS DOM元素

// 为element增加一个样式名为newClassName的新样式 functionaddClass(element, newClassName) { var value =element.className; element.className = value + " " +newClassName; } var bo...

##Jquery基础(三)

Jquery基础-DOM ##一、DOM 是 JavaScript 操作网页的接口,全称为“文档对象模型”(Document Object Model)。它的作用是将网页转为一个 JavaScript 对象,从而可以用脚本进行各种操作(比如增删内容)。 浏览器会根据 DOM 模型,将结构化文档(比如 HTML 和 XML)解析成一系列的节点,再由这些节点组...

react 的一个插件

Reactjs code snippets (vs code 编辑器里面的一个插件 支持 react 得简写) rcc 和 rfc 可以快速生成react代码 下面网址是个react文档: https://materialui-ch.gitbooks.io/material-ui_doc_chinese/content/fu-wu-qi-xuan-ran....

client高性能组件化框架React简单介绍、特点、环境搭建及经常使用语法

【本文源址:http://blog.csdn.net/q1056843325/article/details/54729657 转载请加入该地址】 明天就是除夕了 预祝大家新春快乐 [ ]~( ̄▽ ̄)~* 天天饭局搞得我是身心疲惫= = 所以更新比較慢 今天想跟大家分享的就是这个大名鼎鼎的React框架 简单介绍 React是近两年非常流行的框架...