我尝试过的: 尝试使用 jQuery 更新 React 组件渲染的 DOM 中的类。
通过检查其长度来验证我所针对的类是否存在于 DOM 中,
始终返回 0。 确保 React 组件和 jQuery 代码都正确实现和执行。
期望:
理想情况下,当使用 jQuery 查询 .wpgmp-map-data-container 类时,我期望长度
to be 1, indicating that the class exists in the DOM and can be manipulated accordingly.
首先,确保您的项目中包含 jQuery,可以通过 CDN 或使用 npm 等包管理器安装它。
以下示例展示了如何在安装组件后使用 useEffect() 挂钩运行 jQuery 代码:
import React, { useEffect } from 'react';
import $ from 'jquery'; // Import jQuery
function MyComponent() {
useEffect(() => {
// This code will run after the component is mounted
$('.wpgmp-map-data-container').addClass('new-class');
// Add a new class using jQuery
}, []);
return (
<div className="wpgmp-map-data-container">
{/* Your component JSX */}
</div>
);
}
导出默认的MyComponent; 在此示例中:
但是,我必须再次强调,通常不鼓励将 jQuery 与 React 混合,因为 React 独立管理 DOM。最好尽可能使用状态和属性来处理 React 中的所有 DOM 操作。将 jQuery 与 React 一起使用可能会导致维护问题,因为 React 的虚拟 DOM 和 jQuery 的直接 DOM 操作可能会相互冲突。