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>
    </>
  );
}
相关推荐
小poop2 小时前
CSS 基础与实战:从入门到精通网页美化
前端
Csvn4 小时前
运行时性能
前端
Never_every995 小时前
位图转矢量工具哪个好?实测抠抠图AI位图转矢量工具
大数据·前端
paopaokaka_luck5 小时前
宠物门店经营管理系统(销售与库存联动、进货自动记账、 退换与退款关联、员工个人业绩、ECharts 经营分析、滞销识别与客户分层、宠物档案年龄计算)
前端·javascript·spring boot·mysql·echarts·mybatis·1024程序员节
空中湖6 小时前
用 React 写数据大屏:为什么我不建议用图表库
前端·react.js·前端框架
欣欣之王来了7 小时前
原始HTML插值:v-html指令的使用与安全风险
前端·学习·架构·项目·vue3教程
IT_陈寒7 小时前
Redis的LRU淘汰策略坑了我一整天
前端·人工智能·后端
计算机魔术师7 小时前
砍半价格、参数再涨,国产旗舰追到 Opus 鼻尖了
前端
特立独行的猫A7 小时前
10 MB 的桌面 AI 客户端:用仓颉 + 系统 WebView 替代 Electron
前端·harmonyos
修炼的dance8 小时前
白底图存JPG,sharp开mozjpeg背景杂点少近三成
前端