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>
    </>
  );
}
相关推荐
yuanyxh20 小时前
macOS 应用 - 纯对话生成
前端·macos·ai编程
大家的林语冰20 小时前
ES5 凉凉,Babel 8 正式发布,默认不再编译为 ES5 和 CJS......
前端·javascript·前端工程化
光影少年21 小时前
react批量更新、同步/异步更新场景
前端·react.js·掘金·金石计划
假如让我当三天老蒯21 小时前
模块化:ES Module 与 CommonJS 的区别
前端·面试
用户409501157731721 小时前
Private Forge v2.0 发布:12大前端业务场景技能系统
前端
YFF菲菲兔1 天前
completeRoot 源码解析
react.js
weedsfly1 天前
异步编程全景与事件循环——彻底搞懂 JS 执行机制
前端·javascript
用户059540174461 天前
AI Agent记忆测试踩坑实录:Mock骗了我一周,Mem0+pytest一招破局
前端·css
用户1733598075371 天前
纯前端 PDF 数字签名实战:Vue 3 + pdf-lib 在浏览器里完成签名嵌入
前端·javascript
IT_陈寒1 天前
SpringBoot自动配置的坑,我爬了三天才出来
前端·人工智能·后端