javascript 在 React 中使用 Jquery 的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51304288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the right way to use Jquery in React?
提问by codemt
I am trying to work on a project which is using a Layout/Template which uses a lot of jQuery.
我正在尝试处理一个使用大量 jQuery 的布局/模板的项目。
I have learned to integrate the template with ReactJS Project, however, I am looking for a solution where I can completely replace the jQuery.
我已经学会了将模板与 ReactJS 项目集成,但是,我正在寻找一种可以完全替换 jQuery 的解决方案。
One of my solution is to use jQuery functions inside ComponentDidMount()or Render()function of React.
我的解决方案之一是在React内部使用 jQuery 函数ComponentDidMount()或Render()函数。
Is this approach correct? Is it the right way?
这种方法是否正确?这是正确的方法吗?
I have attached a small example below:
我在下面附上了一个小例子:
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;
});
});
}
This is my RenderFunction.
这是我的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>
回答by Jeremy Thille
Is this approach correct? Is it the right way?
这种方法是否正确?这是正确的方法吗?
No. No approach is correct and there is no right way to use both jQuery and React/Angular/Vue together.
不。没有任何方法是正确的,也没有将 jQuery 和 React/Angular/Vue 一起使用的正确方法。
The reason is that jQuery manipulates the DOM by, for example, selecting elements and adding/deleting stuff into/from them.
原因是 jQuery 操纵 DOM,例如,选择元素并向其中添加/删除内容。
The other frameworks don't manipulate the DOM, they generate it from data, and regenerate it when the data changes.
其他框架不操作 DOM,它们从数据生成它,并在数据更改时重新生成它。
The problem is, jQuery has no clue about React's presence and actions, and React has no clue about jQuery's presence and actions. This will necessarily lead to a broken application, full of hacks and workarounds, unmaintainable, not to mention that you have to load two libraries instead of one.
问题是,jQuery 不知道 React 的存在和动作,而 React 也不知道 jQuery 的存在和动作。这必然会导致应用程序损坏,充满黑客和变通方法,无法维护,更不用说您必须加载两个库而不是一个。
Solution : use jQuery OR React, not both together.
解决方案:使用 jQuery 或 React,不要同时使用。
回答by Manas Jayanth
Is this approach correct? Is it the right way?
这种方法是否正确?这是正确的方法吗?
No. Don't use jQuery to attach event listeners to DOM elements created and managed by React. Use onClick'. I could not find#sidebarCollapse` in your snippet. It could look something like this.
不。不要使用 jQuery 将事件侦听器附加到由 React 创建和管理的 DOM 元素。onClick'. I could not find在您的代码段中使用#sidebarCollapse`。它可能看起来像这样。
<button id="sidebarCollapse" onClick={state => this.setState({ collapsed: !state.collapsed })>Collapse</button
And the class for <nav id="sidebar">could dependent on this state
并且类<nav id="sidebar">可能依赖于这个状态
<nav id="sidebar" className={ this.state.collapsed ? "": "active" } >
You'll notice, you hand over running operations like adding removing class, attributes and other DOM operations to React and simply declare how things must react to state changes. Amidst this, if you try to run jQuery operations, your UI could probably end up in an inconsistent state.
您会注意到,您将正在运行的操作(例如添加删除类、属性和其他 DOM 操作)移交给 React,并简单地声明事物必须如何对状态更改做出反应。在此期间,如果您尝试运行 jQuery 操作,您的 UI 可能最终会处于不一致的状态。
Migration could be done like this: replace parts of your UI elements with React. For eg, initially you could do,
迁移可以这样完成:用 React 替换部分 UI 元素。例如,最初你可以这样做,
<!-- rest of your existing jQuery based code -->
<header id="reactManagedNavbar">
<!-- Nothing here. React will take care of DOM Elements here -->
</header>
<!-- rest of your existing jQuery based code -->
And React side could look like this,
而 React 方面可能看起来像这样,
// main.js
ReactDOM.render(<MyNavBar />, document.getElementById('reactManagedNavBar'))
// MyNavBar.js could have the react components
This way you can incrementally migrate to React and still have jQuery side by side. Just dont manipulate the each other DOM elements.
通过这种方式,您可以逐步迁移到 React,并且仍然可以并排使用 jQuery。只是不要操作彼此的 DOM 元素。
Sometimes you need a jQuery plugins (animations, visualisations charts etc) inside a React component. Use refs!
有时您需要在 React 组件中使用 jQuery 插件(动画、可视化图表等)。使用参考!
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 */}
<div ref={this.myRef} />
{/* rest of React elements */}
);
}
}
Again, refrain from touching your jQuery's DOM in React and vice versa.
同样,不要在 React 中接触 jQuery 的 DOM,反之亦然。
回答by Daniel Amos
jQuery and react can very well when together only if they don't interact with each other. If you choose to use jQuery use only jQuery to manipulate the dom not both. And way is to use jQuery outside the react Js file in your index.html Please note: this will work only if the page you query loads first
只有当 jQuery 和 react 不相互交互时,它们才能很好地结合在一起。如果您选择使用 jQuery,请仅使用 jQuery 来操作 dom,而不是同时使用两者。方法是在 index.html 中的 react Js 文件之外使用 jQuery 请注意:这仅在您查询的页面首先加载时才有效
回答by Ricardo Gonzalez
I've recommend you to use a provider plugin in your webpack.config:
我建议您在 webpack.config 中使用提供程序插件:
Is really simple to use, and it allows you to use jquery in all your project without importing the package in every file:
使用起来非常简单,它允许您在所有项目中使用 jquery,而无需在每个文件中导入包:
More Info Docs: https://webpack.js.org/plugins/provide-plugin/?
更多信息文档:https: //webpack.js.org/plugins/provide-plugin/?
So you just have to add this plugin in your webpack.config file:
所以你只需要在你的 webpack.config 文件中添加这个插件:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
});

