首页 > web前端 > js教程 > 正文

理解 React 中的 Refs 和 DOM:访问和操作 DOM 元素

DDD
发布: 2024-12-19 17:39:19
转载
981人浏览过

react 中的 refs 和 dom:访问和操作 dom 元素

在 react 中,refs 用于直接访问 dom 元素 并与之交互。虽然 react 通常通过状态和 props 以声明式方式管理 dom,但有时您可能需要直接与 dom 交互,例如动画、表单字段焦点或测量元素尺寸。在这些情况下,refs 提供了一种访问底层 dom 节点的方法。


1. react 中的 refs 是什么?

a refreference 的缩写)是一个允许你引用 dom 元素或 react 组件实例的对象。可以在类组件中使用 react.createref() 或在函数组件中使用 useref() 创建 ref。参考文献通常用于:

  • 直接访问 dom(例如,聚焦输入字段或获取表单元素的值)。
  • 触发命令式动画或动作。
  • 与需要直接 dom 操作的第三方库集成。

2.创建和使用参考

类组件:

在类组件中,引用是使用 react.createref() 创建的。然后,创建的 ref 通过 ref 属性附加到 dom 元素。

类组件中的引用示例:

import react, { component } from 'react';

class mycomponent extends component {
  constructor(props) {
    super(props);
    // create a ref to access the input element
    this.inputref = react.createref();
  }

  handlefocus = () => {
    // access the dom node directly and focus the input element
    this.inputref.current.focus();
  };

  render() {
    return (
      <div>
        <input ref={this.inputref} type="text" />
        <button onclick={this.handlefocus}>focus input</button>
      </div>
    );
  }
}

export default mycomponent;
登录后复制

在此示例中:

  • this.inputref 是使用 react.createref() 创建的。
  • ref 通过 ref 属性分配给 元素。
  • 在handlefocus方法中,我们通过this.inputref.current访问输入元素并调用focus()以编程方式聚焦输入字段。

在函数组件中:

在函数组件中,引用是使用 useref 钩子创建的。 useref 钩子允许您创建一个在重新渲染期间持续存在的可变引用对象。

函数组件中的引用示例:

import react, { useref } from 'react';

const mycomponent = () => {
  const inputref = useref();

  const handlefocus = () => {
    // access the dom node directly and focus the input element
    inputref.current.focus();
  };

  return (
    <div>
      <input ref={inputref} type="text" />
      <button onclick={handlefocus}>focus input</button>
    </div>
  );
};

export default mycomponent;
登录后复制

在此示例中:

  • inputref 是使用 useref 钩子创建的。
  • 使用 ref 属性将 ref 附加到 元素。
  • handlefocus 函数使用 inputref.current 访问输入元素,并调用 focus() 来聚焦输入字段。

3.参考用例

a.访问 dom 元素

refs 通常用于直接访问和操作 dom 元素。例如,可以使用 refs 轻松完成关注文本输入或测量元素的大小。

b.管理焦点

refs 允许您管理元素的焦点,例如在组件安装时或在执行特定操作后聚焦于输入字段。

使用参考文献管理焦点的示例:

import react, { useeffect, useref } from 'react';

const focusinput = () => {
  const inputref = useref();

  useeffect(() => {
    // focus the input when the component mounts
    inputref.current.focus();
  }, []);

  return <input ref={inputref} type="text" />;
};

export default focusinput;
登录后复制

在此示例中,由于 useeffect 挂钩和 ref,当组件安装时,输入会自动聚焦。

AISEO ART
AISEO ART

AISEO平台的艺术图片生成器

AISEO ART 35
查看详情 AISEO ART

c.触发动画或与第三方库集成

refs 通常用于与第三方库交互或触发命令式动画。例如,您可以使用 ref 来控制自定义动画或与 jquery 等非 react 库交互。

d.表单验证

refs 还可以用于收集表单数据,而无需将数据存储在 react 的状态中,为不需要实时更新的表单提供了一个简单的替代方案。


4.管理多个元素的引用

使用多个元素时,您可以将引用存储在对象或数组中以访问每个元素。

多个元素的引用示例:

import React, { useRef } from 'react';

const MultipleRefs = () => {
  const inputRefs = [useRef(), useRef(), useRef()];

  const focusInput = (index) => {
    inputRefs[index].current.focus();
  };

  return (
    <div>
      <input ref={inputRefs[0]} type="text" />
      <input ref={inputRefs[1]} type="text" />
      <input ref={inputRefs[2]} type="text" />
      <button onClick={() => focusInput(1)}>Focus Second Input</button>
    </div>
  );
};

export default MultipleRefs;
登录后复制

在此示例中,使用引用数组管理多个输入元素,并使用按钮来聚焦第二个输入。


5. refs 与 state

refs 提供了一种与 dom 交互的方式,而 react 中的 state 用于管理影响 ui 渲染的数据。了解何时使用它们非常重要:

  • 状态用于动态渲染:当数据发生变化并影响ui的渲染方式时,使用状态。
  • refs 用于命令式操作:当您需要直接与 dom 元素交互(例如,聚焦、测量或触发动画)时,请使用 refs。

6.结论

react 中的 refs 是直接访问和操作 dom 元素的强大功能。它们提供了与 ui 交互的命令式方式,支持聚焦输入字段、触发动画或与第三方库集成等操作。

虽然 react 鼓励使用状态和 props 的声明式方法,但当您需要与 dom 进行更直接的交互时,refs 是一个重要的工具。

以上就是理解 React 中的 Refs 和 DOM:访问和操作 DOM 元素的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号