在React中使用Jquery的正确方法是什么?
我正在尝试使用一个使用大量jQuery的布局/模板的项目。
我已经学会了将模板与ReactJS Project集成,但是,我正在寻找一个可以完全替换jQuery的解决方案。
我的解决方案之一是在React的ComponentDidMount()
或Render()
函数中使用jQuery函数。
这种方法是否正确? 这是正确的方法吗?
我在下面附上了一个小例子:
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
function。
{/* */} {/* */ } { /* */ }
这种方法是否正确? 这是正确的方法吗?
没有。没有方法是正确的,没有正确的方法同时使用jQuery和React / Angular / Vue。
原因是jQuery操纵DOM,例如,选择元素并在其中添加/删除内容。
其他框架不操纵DOM,它们从数据生成它,并在数据更改时重新生成它。
问题是,jQuery对React的存在和操作没有任何线索,React对jQuery的存在和操作没有任何线索。 这必然导致应用程序损坏,充满黑客和变通方法,无法维护,更不用说你必须加载两个库而不是一个。
解决方案:使用jQuery OR React,而不是两者一起使用。
这种方法是否正确? 这是正确的方法吗?
不。不要使用jQuery将事件侦听器附加到由React创建和管理的DOM元素。 使用onClick'. I could not find
onClick'. I could not find
在你的代码片段中onClick'. I could not find
#sidebarCollapse`。 它可能看起来像这样。
可能依赖于此状态
您会注意到,您将运行操作移交给React,例如向React添加删除类,属性和其他DOM操作,并简单地声明事物必须如何对状态更改做出反应。 在这种情况下,如果您尝试运行jQuery操作,您的UI可能最终会处于不一致状态。
可以像这样进行迁移:用React替换部分UI元素。 例如,最初你可以这样做,
而React方面看起来像这样,
// main.js ReactDOM.render( , document.getElementById('reactManagedNavBar')) // MyNavBar.js could have the react components
通过这种方式,您可以逐步迁移到React,并且仍然可以并行使用jQuery。 只是不要操纵彼此的DOM元素。
有时你需要在React组件中使用jQuery插件(动画,可视化图表等)。 使用refs!
class MyJQueryDependingComp extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } componentDidMount() { // this.myRef.current is the dom element. Pass it to jQuery } render() { return ( {/* rest of React elements */} {/* rest of React elements */} ); } }
再次,不要在React中触摸jQuery的DOM,反之亦然。