无法使用 jQuery 更新 React 渲染的 DOM 类

问题描述 投票:0回答:1

我尝试过的: 尝试使用 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.

javascript jquery reactjs
1个回答
0
投票

首先,确保您的项目中包含 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; 在此示例中:

  1. 我们使用 import $ from 'jquery'; 在文件顶部导入 jQuery。
  2. 在 useEffect() 挂钩内,我们执行 jQuery 代码。在这里,我们将一个新类 new-class 添加到类为 wpgmp-map-data-container 的元素中。
  3. 空依赖数组 [] 作为 useEffect() 的第二个参数,确保该效果在组件安装后仅运行一次。

但是,我必须再次强调,通常不鼓励将 jQuery 与 React 混合,因为 React 独立管理 DOM。最好尽可能使用状态和属性来处理 React 中的所有 DOM 操作。将 jQuery 与 React 一起使用可能会导致维护问题,因为 React 的虚拟 DOM 和 jQuery 的直接 DOM 操作可能会相互冲突。

© www.soinside.com 2019 - 2024. All rights reserved.