You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React TypeScript中使用useRef选择伪元素

在React TypeScript中操作元素伪元素的方案

DOM API无法直接选中伪元素(比如:before/:after),因为它们不属于真实的DOM节点,只是CSS渲染出来的虚拟元素。不过可以通过以下几种方式间接控制或获取伪元素的状态:

1. 用CSS变量动态控制伪元素样式

这是最常用的动态修改伪元素的方式,通过给宿主元素设置CSS变量,让伪元素继承变量值:

示例代码

/* style.module.css */
.header {
  /* 定义CSS变量 */
  --pseudo-bg-color: #ccc;
  position: relative;
}

.header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  /* 使用CSS变量 */
  background-color: var(--pseudo-bg-color);
}
import { useRef, useEffect } from 'react';
import style from './style.module.css';

const YourComponent = () => {
  const header = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (header.current) {
      // 动态修改CSS变量,间接改变伪元素样式
      header.current.style.setProperty('--pseudo-bg-color', '#ff0000');
    }
  }, []);

  return <div className={style.header} ref={header}>Hello World</div>;
};

export default YourComponent;

2. 通过切换类名修改伪元素样式

预先定义好不同状态下的伪元素样式,通过给宿主元素添加/移除类来切换伪元素表现:

示例代码

/* style.module.css */
.header {
  position: relative;
}

.header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #ccc;
  transition: width 0.3s;
}

/* 激活状态下的伪元素样式 */
.header.active::after {
  width: 50%;
  background-color: #2196f3;
}
import { useRef, useEffect } from 'react';
import style from './style.module.css';

const YourComponent = () => {
  const header = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (header.current) {
      // 添加类名触发伪元素样式变化
      header.current.classList.add(style.active);
      // 也可以用classNames库管理类名
      // header.current.className = classNames(style.header, style.active);
    }
  }, []);

  return <div className={style.header} ref={header}>Hello World</div>;
};

export default YourComponent;

3. 获取伪元素的计算样式(仅读取)

如果只是需要获取伪元素的当前渲染样式,可以用window.getComputedStyle方法:

示例代码

import { useRef, useEffect } from 'react';
import style from './style.module.css';

const YourComponent = () => {
  const header = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (header.current) {
      // 获取:after伪元素的计算样式
      const pseudoStyle = window.getComputedStyle(header.current, ':after');
      // 读取具体属性,比如背景色
      const bgColor = pseudoStyle.backgroundColor;
      console.log('伪元素背景色:', bgColor);
    }
  }, []);

  return <div className={style.header} ref={header}>Hello World</div>;
};

export default YourComponent;

内容的提问来源于stack exchange,提问作者BlackDragon94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:37:13