当前位置:首页 > React

html中的对象react如何获取

2026-01-25 23:09:05React

React 中获取 DOM 对象的方法

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

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

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 场景)

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 元素:

html中的对象react如何获取

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() 将内容插入到选定元素的内部末尾。 $("#…

vue对象监听如何实现

vue对象监听如何实现

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

html使用vue实现秒表

html使用vue实现秒表

使用Vue实现秒表 以下是一个基于Vue的秒表实现方案,包含开始、暂停、重置功能,并显示时、分、秒和毫秒。 核心代码实现 <template> <div class="stop…

react如何渲染html

react如何渲染html

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

react如何获取window对象

react如何获取window对象

获取 window 对象的方法 在 React 中,window 对象是全局的浏览器 API,可以直接访问。以下是几种常见的使用场景: 直接访问全局对象 const windowWidth = w…

react如何定义可扩展的对象

react如何定义可扩展的对象

定义可扩展对象的方法 在React中定义可扩展对象通常涉及使用JavaScript的原型继承、类继承或组合模式。以下是几种常见的方法: 使用类继承 通过class和extends实现对象的扩展性。子…