让 React 组件与 jQuery 监听器一起工作 [英] Getting React component to work with jQuery listener

查看:17
本文介绍了让 React 组件与 jQuery 监听器一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然这不是解决问题的最佳方法,但我确实需要我的 React 应用程序与 jQuery 交互,直到我想出更好的解决方案.

在我的入口点组件的 HTML 页面中,我有一个简单的 jQuery 侦听器——见下文:

...//为简洁起见省略<身体>...//为简洁起见省略<script type="text/javascript">$(".my-class").on("click", function() {调试器;//我们会在这里做一些事情})</html>

然后,在我的愚蠢组件中,我有以下内容但它不起作用.当我单击按钮时,我没有到达我在侦听器中设置的断点.

const MyComponent = () =>{返回(<div><a href="#" className="btn-primary my-class">点击我!</a>

);}导出默认的 MyComponent;

知道如何让它发挥作用吗?

解决方案

在 ready handler 中添加你的方法:

jQuery(function($) {//你的代码在这里});

<小时>

此外,您可以在 componentDidMount 钩子中调用 jQuery 方法:

componentDidMount() {//你的 jQuery 代码在这里}

<小时>

如果您不想在组件本身中挂钩您的 jquery 方法而只是在 html 中使用,那么您还需要在您的文件中注入 React 和 ReactDom:

//index.js从'反应'导入{反应}导入 { ReactDom } from 'react-dom'从'jQuery'导入{$}//index.html<script src="index.js"></script><!-- 你的 jquery 钩子 -->

Though this is not the best approach to the problem, I do need my React app to interact with jQuery till I come up with a better solution.

In the HTML page for my entry point component, I have a simple jQuery listener -- see below:

<html>
... // Omitted for brevity
<body>
... // Omitted for brevity
<script type="text/javascript">

   $(".my-class").on("click", function() {
      debugger;
      // We'll do something here
   })

</script>
</body>
</html>

Then, in my dumb component, I have the following but it's not working. When I click my button, I'm not hitting the break point I set in the listener.

const MyComponent = () => {
   return(
      <div>
         <a href="#" className="btn-primary my-class">Click Me!</a>
      </div>
   );
}

export default MyComponent;

Any idea how I can get this to work?

解决方案

Add your method inside ready handler:

jQuery(function($) {
  // your code here
});


Also, you may call the jQuery method in the componentDidMount hook:

componentDidMount() {
  // your jQuery code here
}


If you don't want to hook your jquery method in the component itself and just use in the html, then you also need to inject the React and the ReactDom in your file:

// index.js
import { React } from 'react'
import { ReactDom } from 'react-dom'
import { $ } from 'jQuery'

// index.html
<script src="index.js"></script>
<!-- your jquery hook -->

这篇关于让 React 组件与 jQuery 监听器一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆