JavaScript编程上.click()不会在ReactJS元素中触发

JavaScript programmatically .click() is not triggered in ReactJS element

本文关键字:ReactJS 元素 编程 click JavaScript      更新时间:2023-09-26

我正在尝试以编程方式单击react JS元素。

例如,请查看此链接:点击这里

我无法点击样品图片,这会改变产品的主图片。

我尝试了下面的代码:

document.querySelector('#product-selection-4476800 > section.np-sku-filters > div.np-circular-swatches.small > ul > li:nth-child(2) > a').click();
document.querySelector('#product-selection-4476800 > section.np-sku-filters > div.np-circular-swatches.small > ul > li:nth-child(2) > a > span > img').click();

两个都不工作。我也试过

function clickElement(el){
    var ev = document.createEvent("MouseEvent");
    ev.initMouseEvent(
        "click",
        window, null,
        false, false, false, false,
        0, null
    );
    el.dispatchEvent(ev);
}

元素仍然没有改变。

谢谢!

我找到了一个解决方案,从外部点击它的DOM的ReactJS元素。

var elm = document.querySelector('#product-selection-4476800 > section.np-sku-filters > div.np-circular-swatches.small > ul > li:nth-child(2) > a');
function triggerEvents(n, e){
    var ev = document.createEvent('MouseEvents');
    ev.initEvent(e, true, true);
    n.dispatchEvent(ev);
}
triggerEvents(elm, "mouseover");
triggerEvents(elm, "mousedown");
triggerEvents(elm, "click");
triggerEvents(elm, 'mouseup');

并按预期工作

感谢所有人的时间和回复。:)