一文搞懂React的ref

本文详细介绍了在React中如何使用ref,包括refs转发的必要性,解决ref传递问题的方案如React.forwardRef、回调Refs和useImperativeHandle,以及createRef和useRef的创建与应用。
摘要由CSDN通过智能技术生成

目录

refs转发

Ref 转发是一项将 ref 自动地通过组件传递到其一子组件的技巧,Ref 转发使组件可以像暴露自己的 ref 一样暴露子组件的 ref。

下面是几个适合使用 refs 的情况:

  • 管理焦点,文本选择或媒体播放。
  • 触发强制动画。
  • 集成第三方 DOM 库。

避免使用 refs 来做任何可以通过声明式实现来完成的事情。

ref 的作用是获取实例,可能是 DOM 实例,也可能是 ClassComponent 的实例,但是不能在函数组件上使用 ref 属性,因为函数组件没有实例

ref使用中的问题

  • ref 不能通过props进行传递,和key一样。
  • 将组件包装成高阶组件(HOC),无法通过ref去获取包装前的组件实例
  • 如果目标对象时函数组件,传递ref会报错,那么怎样才能使用ref去获取函数组件呢?

1、问题:HOC中ref不能向下传递

// Log.js
import React, {
    Component } from 'react'

const Log = MyComponent => {
   
    class Logout extends Component {
   
        componentDidMount() {
   
            console.log('did mount')
        }

        componentDidUpdate(prevProps, prevState) {
   
            console.log('did update')
        }

        render() {
   
            return (<MyComponent {
   ...this.props} />);
        }
    }
    return Logout
}

export default Log;

访问ref时,实际指向的是Logout容器组件,并不是包装前的组件Detail

import log from '../Log'
import Detail from '../Detail'

const Logout = log(Detail)
<Logout ref={
   ref} />

2、ref不能在函数组件上使用,会报错

// 函数组件
function MyFunctionComponent() {
   
  return <input />;
}

class Parent extends React.Component {
   
  constructor(props) {
   
    super(props);
    this.textInput = React.createRef();
  }
  render() {
   
    // This will *not* work!
    return 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值