简体   繁体   English

事件 onClick 与 React - function 未调用

[英]Event onClick with React - function not called

I have a Js file with some functions inside.我有一个 Js 文件,里面有一些函数。

const addProductToCart = document.querySelectorAll('.add-product-to-cart');

ProductToCart.forEach(el => {
        el.addEventListener('click', e => {
            const redirect = e.target.dataset.redirect;
            if (!redirect) {
                e.preventDefault();
            }
            let product = e.target.dataset.product
            if (product) {
                fetch(baseUrl + "cookie/product/" + product,
                    {method: 'POST'}
                ).then(r => console.log(r))
            }
            animateIcon.animate(translations["Your sample has been successfully added to your cart"], 'cart');
        });
    }); 

With inspection of the HTML code I can see event on each product:通过检查 HTML 代码,我可以看到每个产品的事件: HTML 检查代码

My function to add a sample works, but not in my render React (I just added the name of the class).我的 function 添加了一个示例作品,但不在我的渲染 React 中(我只是添加了类的名称)。

<a href={""} className={"add-product-to-cart"} data-product={product.id}>Test</a>

But in this case, I can't see the event and my function is not called:但在这种情况下,我看不到该事件,并且我的 function 没有被调用: 在此处输入图像描述

So: Why my Js doesn't work on this page, is there something to add/do about "event" works?所以:为什么我的 Js 在这个页面上不起作用,关于“事件”工作有什么要添加/做的吗? What can I do to import all logic from another Js file.我该怎么做才能从另一个 Js 文件中导入所有逻辑。

Thanks in advance, I am new to React...在此先感谢,我是 React 的新手...

Without seeing the rest of your react component its difficult to tell but if the function isnt being called did you bind it?没有看到你的反应组件的 rest 很难分辨,但是如果 function 没有被调用,你绑定它了吗?

class YOURNAME extends React.Component {
constructor(props) {
  super(props)
  this.addProductToCart = this.addProductToCart.bind(this);
}

Then outline the function然后勾勒出function

addProductToCart(){
//what you want to do here

} }

Your current button is fine.您当前的按钮很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM