React useRef 组件内及组件传参使用

保存变量, 改变不引起渲染
js 复制代码
import { useRef} from 'react';
const dataRef = useRef(null)
...
dataRef.current = setTimeout(()=>console.log('...'),1000)
绑定dom
js 复制代码
const inputRef = useRef(null)
<input ref = {inputRef} />
绑定dom列表 - ref 回调
js 复制代码
const itemsRef = useRef({})
{catList.map(cat => (
  <li
    key={cat.id}
    ref={(node) => {
      const map = getMap();
      if (node) {
        itemsRef.current[cat.id] = node;
      } else {
        delete itemsRef.current[cat.id]
      }
    }}
  >
    {cat.id}
  </li>
))}
访问子组件属性

将 ref 放在自定义组件上,默认情况下会得到 null。因为默认情况下,React 不允许组件访问其他组件的 DOM 节点。手动操作另一个组件的 DOM 节点会使你的代码更加脆弱。

想要暴露其 DOM 节点的组件必须选择该行为。一个组件可以指定将它的 ref "转发"给一个子组件。

js 复制代码
// 父组件
const inputRef = useRef(null);
<MyInput ref={inputRef} /> // 1. 告诉 React 将对应的 DOM 节点放入 inputRef.current 中。但是这取决于 MyInput 组件是否允许,默认不允许。

// 子组件 MyInput 
import { forwardRef } from 'react';
const MyInput = forwardRef((props, ref) => { // 2. forwardRef 接受父组件的 inputRef 作为第二个参数 ref 传入组件,第一个参数是 props。
  return (
  	<input {...props} ref={ref} /> // 3. 将 ref 传递给 <input>
  )
});
使用 useImperativeHandle 暴露 API
js 复制代码
import { forwardRef, useRef, useImperativeHandle } from 'react';

const MyInput = forwardRef((props, ref) => {
  const realInputRef = useRef(null);
  useImperativeHandle(ref, () => ({
    // 只暴露 focus,没有别的
    focus() {
      realInputRef.current.focus();
    },
  }));
  return <input {...props} ref={realInputRef} />;
});

export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <MyInput ref={inputRef} />
      <button onClick={handleClick}>
        聚焦输入框
      </button>
    </>
  );
}
相关推荐
志尊宝3 分钟前
Vue3 零基础每日笔记(026):emit 子传父——defineEmits 与事件校验
前端·javascript·html·vue3
风骏时光牛马11 分钟前
6个高频实用技术脚本案例,覆盖运维与办公自动化(可直接复用)
前端
ssshooter25 分钟前
Node.js 天生就是异步的,为什么还要消息队列?
javascript·后端·面试
爱吃红星柚26 分钟前
【学习】Elpis 抽离与发布 npm 包
前端·前端框架·node.js
PedroQue991 小时前
0.5.0重磅发布:动画插件+H5体验全面优化
前端·uni-app
金虹桥程序员1 小时前
【动画】 📚 CSS 动画与 GPU 合成层优化全链路指南
前端·面试
程序员老赵1 小时前
Docker 部署填鸭表单完整教程:搭建私有化问卷与表单收集平台
前端·docker·开源
无限压榨切图仔1 小时前
向量库能搜到内容,为什么还不算学会 RAG
前端·agent
mmsx1 小时前
MapLibre 实战 11|用户说"我的地块丢了":一个 sealed class 图层模型,和四个让我重构三版的坑
android·前端·开源
xqchen1 小时前
代码差异可视化方案选型:diff2html 实战指南
前端