当前位置:首页 > React

html中的对象react如何获取

2026-01-25 23:09:05React

React 中获取 DOM 对象的方法

在 React 中,可以通过 ref 来获取 DOM 对象或组件实例。以下是几种常见的方式:

使用 useRef Hook(函数组件推荐)

html中的对象react如何获取

import { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

使用 createRef(类组件)

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  handleClick = () => {
    this.inputRef.current.focus();
  };

  render() {
    return (
      <div>
        <input ref={this.inputRef} type="text" />
        <button onClick={this.handleClick}>Focus Input</button>
      </div>
    );
  }
}

回调 Refs(适用于动态 ref 场景)

html中的对象react如何获取

function MyComponent() {
  let inputRef = null;

  const handleClick = () => {
    inputRef.focus();
  };

  return (
    <div>
      <input ref={el => inputRef = el} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

获取子组件实例

通过 ref 也可以获取子组件的实例(仅限类组件):

class Child extends React.Component {
  method() {
    console.log('Child method called');
  }

  render() {
    return <div>Child Component</div>;
  }
}

class Parent extends React.Component {
  childRef = React.createRef();

  handleClick = () => {
    this.childRef.current.method();
  };

  render() {
    return (
      <div>
        <Child ref={this.childRef} />
        <button onClick={this.handleClick}>Call Child Method</button>
      </div>
    );
  }
}

转发 Refs(获取子组件 DOM)

使用 React.forwardRef 可以获取子组件内部的 DOM 元素:

const Child = React.forwardRef((props, ref) => {
  return <input ref={ref} {...props} />;
});

function Parent() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <Child ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

注意事项

  • 函数组件默认不能直接通过 ref 获取实例(除非使用 forwardRef
  • ref 不应过度使用,优先考虑 React 的状态驱动原则
  • 避免在渲染期间修改 ref.current,应在事件处理或副作用中操作

标签: 对象html
分享给朋友:

相关文章

jquery 插入html

jquery 插入html

jQuery 插入 HTML 的方法 jQuery 提供了多种方法来动态插入 HTML 内容到 DOM 中。以下是几种常用的方法: append() 将内容插入到选定元素的内部末尾。 $(…

css与html制作

css与html制作

CSS与HTML制作基础 HTML(超文本标记语言)和CSS(层叠样式表)是构建网页的核心技术。HTML负责网页的结构和内容,CSS负责样式和布局。以下是两者的基本使用方法。 HTML基础结构 HT…

vue对象监听如何实现

vue对象监听如何实现

Vue 对象监听实现方法 Vue 提供了多种方式监听对象的变化,以下是常见的实现方法: 使用 watch 选项 在 Vue 实例中通过 watch 选项监听对象变化: new Vue({…

react如何展示html

react如何展示html

渲染原始 HTML 在 React 中直接渲染原始 HTML 需要使用 dangerouslySetInnerHTML 属性。该属性接收一个对象,其中 __html 键对应的值是需要渲染的 HTML…

react如何渲染html

react如何渲染html

渲染HTML字符串的方法 在React中渲染HTML字符串需要使用dangerouslySetInnerHTML属性。该属性允许直接插入HTML内容,但需谨慎使用以避免XSS攻击。 functio…

react如何修改对象

react如何修改对象

修改 React 中的对象 在 React 中修改对象时,需要遵循不可变性原则,即不直接修改原对象,而是创建新对象。以下是几种常见方法: 使用扩展运算符(浅拷贝) const [user, setU…