在 React 中使用 Jquery 的正确方法是什么? [英] What is the right way to use Jquery in React?

查看:32
本文介绍了在 React 中使用 Jquery 的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理一个使用了大量 jQuery 的布局/模板的项目.

我已经学会了将模板与 ReactJS 项目集成,但是,我正在寻找一种可以完全替代 jQuery 的解决方案.

我的解决方案之一是在 React 的 ComponentDidMount()Render() 函数中使用 jQuery 函数.

这种方法正确吗?方法对吗?

我在下面附上了一个小例子:

import React, { Component } from 'react';导入'../stylesheets/commonstyles.css';导入'../stylesheets/bootstrap-sidebar.css';导入'../stylesheets/sidebar1.css';从'jquery'导入$;类导航栏扩展组件{构造函数(道具){超级(道具);this.openSidebar = this.openSidebar.bind(this);}打开侧边栏(){console.log('你好侧边栏');}componentWillMount(){$(document).ready(function () {$('#sidebarCollapse').on('click', function () {$('#sidebar').toggleClass('active');});$('.search-btn').on("click", function () {$('.search').toggleClass("search-open");返回假;});});}

这是我的Render函数.

{/* */}<div class="wrapper" style={{paddingTop:60}}>{/* <!-- 侧边栏支架-->*/}<nav id="侧边栏"><div class="sidebar-header"><h3>仪表板</h3><strong>BS</strong>

<ul class="list-unstyled components"><li class="active"><a href="#homeSubmenu"/*data-toggle="collapse" */aria-expanded="false"><i class="ti-home"></i>家</a><ul class="collapse list-unstyled" id="homeSubmenu"><li><a href="#">首页 1</a></li><li><a href="#">首页 2</a></li><li><a href="#">首页 3</a></li><li><a href="#" style={{color:"white"}}><i class="ti-align-justify" ></i>关于</a><a href="#pageSubmenu"/*data-toggle="collapse" */aria-expanded="false" style={{color:"white"}}><i class="ti-text"></i>页面</a><ul class="collapse list-unstyled" id="pageSubmenu"><li><a href="#">第 1 页</a></li><li><a href="#">第 2 页</a></li><li><a href="#">第 3 页</a></li><li><a href="#" style={{color:"white"}}><i class="ti-paragraph"></i>文件夹</a><li><a href="#" style={{color:"white"}}><i class="ti-control-play"></i>常问问题</a><li><a href="#" style={{color:"white"}}><i class="ti-share-alt"></i>接触</a></nav>{/* */}<div id="内容">

解决方案

这种方法正确吗?方法对吗?

没有.没有一种方法是正确的,也没有将 jQuery 和 React/Angular/Vue 一起使用的正确方法.

jQuery 通过例如选择元素并向其中添加/删除内容来操作 DOM.通常,它选择现有的

并设置其文本.

其他框架不操作DOM;他们从数据中生成它,并在数据发生变化时重新生成它(例如在 Ajax 调用之后).

问题是,jQuery 不知道 React 的存在和动作,而 React 也不知道 jQuery 的存在和动作.

这必然会导致应用程序损坏,充满黑客和变通方法,无法维护,更不用说您必须加载两个库而不是一个.

例如,jQuery 将选择一个

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆