react 的 createRef 和 useRef 的区别

ref 是什么

ref 是一个普通的 JavaScript 对象,拥有一个名为 current 的属性。

修改 ref 的 current 值不会触发组件重新渲染。

为什么要使用 ref

当想要用一些数据但又不想让这些数据触发新的渲染时,或者在子父组件通信中,就可以使用 ref 。

创建 ref 的方式

通过回调函数

通过回调函数创建的 ref 没有 .current 属性

import { Component } from 'react'
class App extends Component{
   handleClick = () => {
   	this.inputRef.focus()
   }
   render() {
   	return (
   		<div>
       <input ref={ref => this.inputRef = ref} />
       <button onClick={this.handleClick}>获取 input 框焦点</button>
     </div>
   )
   }
}

使用 createRef

调用 createRef 在 class 组件中声明一个 ref,createRef 不接收任何参数。
调用 createRef 声明的 ref 会在组件每次渲染的时候重新创建,每次渲染都会返回一个新的引用。

import { Component, createRef } from 'react'
class App extends Component {
 inputRef = createRef();
 handleClick = () => {
   this.inputRef.current.focus();
 };
 render() {
   return (
     <div>
       <input ref={this.inputRef} />
       <button onClick={this.handleClick}>获取 input 框焦点</button>
     </div>
   );
 }
}

使用 useRef

函数组件中使用 useRef 来创建 ref。接收一个任意初始值,如字符串、对象,甚至是函数等。
使用 useRef 创建的 ref 只会在组件首次渲染时创建,每次都会返回相同的引用,所以通过 ref 可以拿到最新的值。

import { useRef } from 'react';
const App = () => {
const inputRef = useRef(null);
const countRef = useRef(1);

const handleClick = () => {
  inputRef.current.focus();
};
const handleClick2 = () => {
  countRef.current = countRef.current + 1;
  console.log('countRef.current', countRef.current)
};
return (
  <div>
    <input ref={inputRef} />
    <button onClick={handleClick}>获取 input 框焦点</button>
    <div>CountRef: {countRef.current}</div>
    <button onClick={handleClick2}>count + 1</button>
  </div>
);
};

![在这里插入图片描述](https://img-blog.csdnimg.cn/9d4ae9fa84c940bf95a7dbdba4de0274.png

使用场景

  1. 操作 DOM,例如:点击按钮让输入框聚焦(例子如上)
  2. 子父组件通信:父组件可以通过使用 ref 来直接调用子组件实例的方法

参考文档:
https://zh-hans.reactjs.org/reference/react/createRef
https://zh-hans.reactjs.org/learn/referencing-values-with-refs#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值