我正在尝试使用一个使用大量jQuery的Layout / Template的项目。
我已经学会了将模板与ReactJS Project集成在一起,但是,我正在寻找一种可以完全替代jQuery的解决方案。
我的解决方案之一是在内部使用jQuery函数ComponentDidMount()或Render()React函数。
ComponentDidMount()
Render()
这种方法正确吗?这是正确的方法吗?
我在下面附上一个小例子:
import React, { Component } from 'react'; import '../stylesheets/commonstyles.css'; import '../stylesheets/bootstrap-sidebar.css'; import '../stylesheets/sidebar1.css'; import $ from 'jquery'; class NavBar extends Component { constructor(props){ super(props); this.openSidebar = this.openSidebar.bind(this); } openSidebar(){ console.log('hello sidebar'); } componentWillMount(){ $(document).ready(function () { $('#sidebarCollapse').on('click', function () { $('#sidebar').toggleClass('active'); }); $('.search-btn').on("click", function () { $('.search').toggleClass("search-open"); return false; }); }); }
这是我的Render职能。
Render
{/* <!--- SIDEBAR -------> */} <div class="wrapper" style={{paddingTop:60}}> {/* <!-- Sidebar Holder --> */ } <nav id="sidebar"> <div class="sidebar-header"> <h3>Dashboard</h3> <strong>BS</strong> </div> <ul class="list-unstyled components"> <li class="active"> <a href="#homeSubmenu" /*data-toggle="collapse" */ aria-expanded="false"> <i class="ti-home"></i> Home </a> <ul class="collapse list-unstyled" id="homeSubmenu"> <li><a href="#">Home 1</a></li> <li><a href="#">Home 2</a></li> <li><a href="#">Home 3</a></li> </ul> </li> <li> <a href="#" style={{color:"white"}}> <i class="ti-align-justify" ></i> About </a> <a href="#pageSubmenu" /*data-toggle="collapse" */ aria-expanded="false" style={{color:"white"}}> <i class="ti-text"></i> Pages </a> <ul class="collapse list-unstyled" id="pageSubmenu"> <li><a href="#">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> </li> <li> <a href="#" style={{color:"white"}}> <i class="ti-paragraph"></i> Portfolio </a> </li> <li> <a href="#" style={{color:"white"}}> <i class="ti-control-play"></i> FAQ </a> </li> <li> <a href="#" style={{color:"white"}}> <i class="ti-share-alt"></i> Contact </a> </li> </ul> </nav> { /* <!-- Page Content Holder --> */ } <div id="content"> </div> </div>
否。没有正确的方法,没有正确的方法同时使用jQuery和React / Angular / Vue。
原因是jQuery通过选择元素并向其中添加内容或从中删除内容来操纵DOM。
其他框架不操纵DOM,而是从数据生成DOM,并在数据更改时重新生成。
问题是,jQuery不了解React的存在和动作,而React不了解jQuery的存在和动作。这必然会导致应用程序损坏,充满hack和变通办法,难以维护,更不用说您必须加载两个库而不是一个。
解决方案:使用jQuery OR React,不能同时使用。