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>
    </>
  );
}
相关推荐
雨季mo浅忆1 分钟前
2999第二项目梳理
前端·项目梳理
炘爚1 分钟前
C++(移动构造、移动赋值、完美转发)
前端·c++
淡忘_cx7 分钟前
解决 Vite EACCES 权限错误:从报错到修复的完整指南
前端·vue
We་ct14 分钟前
LeetCode 191. 位1的个数:两种解法详解
前端·算法·leetcode·typescript
努力的lpp17 分钟前
【小迪安全第14天:前端JS架构信息打点与API接口枚举】
前端·javascript·安全
FreeBuf_30 分钟前
谷歌将Axios npm供应链攻击归因于朝鲜APT组织UNC1069
前端·npm·node.js
前端 贾公子33 分钟前
解决uni-app 输入框,键盘弹起时页面整体上移问题
前端·vue.js·uni-app
南风知我意95739 分钟前
Map 与 WeakMap 深度解析:从内存泄漏到 Vue 3 响应式原理的完整指南
前端·javascript·vue.js