当前位置:首页 > React

react refs 如何使用

2026-03-30 23:22:12React

React Refs 的基本概念

Refs 提供了一种直接访问 DOM 节点或 React 组件实例的方式。通常用于需要直接操作 DOM 的场景,例如焦点管理、动画触发或第三方库集成。

创建 Refs

使用 React.createRef()useRef Hook 创建 ref。类组件中使用 createRef,函数组件中使用 useRef

类组件示例:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

函数组件示例:

function MyComponent() {
  const myRef = React.useRef(null);
  return <div ref={myRef} />;
}

访问 Refs

通过 ref 的 current 属性访问 DOM 节点或组件实例。

function FocusInput() {
  const inputRef = React.useRef(null);

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

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

Refs 与回调 Refs

回调 Refs 是一种更灵活的方式,允许在 ref 附加或分离时执行自定义逻辑。

function CallbackRefExample() {
  const setTextInputRef = (element) => {
    if (element) {
      element.focus();
    }
  };

  return <input ref={setTextInputRef} />;
}

转发 Refs

通过 React.forwardRef 将 ref 传递给子组件,常用于高阶组件或封装库中。

react refs 如何使用

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="fancy-button">
    {props.children}
  </button>
));

function App() {
  const ref = React.useRef(null);
  return <FancyButton ref={ref}>Click Me</FancyButton>;
}

注意事项

  • 避免过度使用 refs,优先考虑 React 的状态和 props 控制。
  • 不要在函数组件中使用 createRef,每次渲染会创建新的 ref 对象。
  • 回调 refs 在组件更新时可能被调用两次(首次传入 null,之后传入 DOM 元素)。

分享给朋友:

相关文章

如何创建react

如何创建react

创建React项目的步骤 使用Create React App工具快速搭建React项目。确保已安装Node.js(版本需≥14.0.0)和npm(版本需≥5.6)。 打开终端或命令行工具,运行以下…

react如何同步

react如何同步

React 同步状态管理方法 在 React 中实现同步状态管理,可以通过以下多种方式实现: 使用 useState 和 useEffect 钩子 通过 useState 定义状态,使用 useEf…

react如何通信

react如何通信

React 组件通信方式 React 组件间的通信方式多样,具体选择取决于组件关系和场景需求。以下是常见方法: 父子组件通信 父组件通过 props 向子组件传递数据,子组件通过回调函数通知父组件…

react如何配置

react如何配置

配置React项目的基本步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过命令行检查版本: node -v npm -v 创建React项目 使用官方工具Creat…

react如何减少setState

react如何减少setState

减少 React 中 setState 调用的方法 合并多次状态更新 使用函数式更新方式合并多次 setState 调用。React 会将多次状态更新批量处理,避免不必要的重新渲染。 // 非函…

react路由如何配置

react路由如何配置

React 路由配置方法 安装 React Router 使用 npm 或 yarn 安装 React Router 的 DOM 版本: npm install react-router-dom #…