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

如何在React的useEffect中调用外部文件的IIFE函数?

解决scoper.js本地导入后无法生效的问题

问题核心

你导入的scoper只是CSS文本处理工具函数,真正实现样式作用域渲染的是scoperProcess;原IIFE会自动执行初始化和处理逻辑,但React组件动态创建的style[scoped]是在IIFE执行后才添加的,自动逻辑抓不到新样式;同时你代码里本地导入和CDN脚本加载共存,造成逻辑冲突。

修复步骤

1. 完善scoper.js的导出

修改scoper.js末尾的导出代码,暴露核心处理函数:

if (typeof exports !== "undefined") {
  exports.scoper = scoper;
  exports.scoperProcess = scoperProcess;
  exports.scoperInit = scoperInit;
}

2. 调整App.js逻辑

去掉CDN脚本加载,在React组件中手动触发scoper逻辑,确保DOM元素挂载后执行:

import React, { useEffect } from "react";
import "./styles.css";
import { scoperInit, scoperProcess } from "./scoper.js";

export default function App() {
  useEffect(() => {
    // 初始化scoper,仅执行一次
    if (!document.querySelector('style[data-scoper-init]')) {
      scoperInit();
      const initMarker = document.createElement('style');
      initMarker.setAttribute('data-scoper-init', '');
      document.head.appendChild(initMarker);
    }

    // 为Hello World所在容器添加scoped红色样式
    let lakersStyle = document.createElement("style");
    lakersStyle.setAttribute("scoped", "");
    lakersStyle.innerHTML = `
      .Puma {
        color: red;
        font-size: 50px;
        text-align: left;
      }
    `;
    document.getElementById("lakers").appendChild(lakersStyle);

    // 为Raptors容器添加scoped紫色样式
    let raptorsStyle = document.createElement("style");
    raptorsStyle.setAttribute("scoped", "");
    raptorsStyle.innerHTML = `
      .Puma {
        color: purple;
        font-size: 50px;
        text-align: left;
      }
    `;
    document.getElementById("raptors").appendChild(raptorsStyle);

    // 手动触发样式作用域处理
    scoperProcess();
  }, []);

  return (
    <>
      <div id="lakers" className="Puma">
        <div>Hello World!</div>
      </div>
      <div id="raptors" className="Puma">
        <h1>Raptors win!</h1>
      </div>
    </>
  );
}

关键说明

  • scoperInit负责初始化基础样式(隐藏body直到处理完成),添加标记避免重复执行。
  • scoperProcess是原IIFE中负责转换scoped样式的核心函数,手动调用可处理动态添加的样式元素。
  • 为两个容器分别添加独立scoped样式,实现Hello World变红、Raptors文字变紫的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:05:15