0

我正在创建一个地理游戏,您应该在世界地图上单击特定国家 - 如果单击右侧,该国家会改变颜色,并且游戏会显示一个可供单击的新国家。如果玩家不知道,他可以点击一个按钮,它会告诉他正确的答案。为此,我想模拟一个单击事件,以便调用相同的 onClick() 函数,就好像您单击了正确的国家一样。

我正在使用 D3,世界地图由 svg 路径组成。下面是我认为可以使用 HTMLElement.click() 方法的代码:

    function simulateClick() {

    // for each index in the nodelist, 
    // if the properties are equal to the properties of currentTargetUnit,
    // simulate a click on the path of that node

    let nodelist = d3.selectAll(".unit")
    for (let i = 0; i < nodelist._groups[0].length; i++) {
        if (nodelist._groups[0].item(i).__data__.properties.filename === currentTargetUnit.properties.filename) {
            console.log(nodelist._groups[0][i])
            // logs the correct svg path element
            nodelist._groups[0][i].click()
            // logs TypeError: nodelist._groups[0][i].click is not a function
        }
    }
}

然后我看了一些教程,这些教程说,出于某种我不完全理解的原因,您宁愿为此使用 React.useRef - 但在他们的所有示例中,他们在返回的元素上放置了一个“ref”值从 React 组件的开头开始,如下所示:

import React, { useRef } from "react";

const CustomTextInput = () => {
  const textInput = useRef();

  focusTextInput = () => textInput.current.focus();

  return (
    <>
      <input type="text" ref={textInput} />
      <button onClick={focusTextInput}>Focus the text input</button>
    </>
  );
}

这显然不起作用,因为我的 svg 路径元素最初没有返回。所以我的问题是——无论是否使用 useRef,我怎样才能做到这一点?

以下是我看过的一些以前的问题,这些问题也没有帮助。 模拟反应元素上的点击事件 反应测试渲染器模拟点击元素 模拟点击反应元素

4

1 回答 1

0

我终于解决了它——我没有调用在节点内设置的 onClick(),而是在以下代码的帮助下创建了一个新的 clickevent:

    function simulateClick() {
    let nodelist = d3.selectAll(".unit")
    for (let i = 0; i < nodelist._groups[0].length; i++) {
        if (nodelist._groups[0].item(i).__data__.properties.filename === currentTargetUnit.properties.filename) {
            var event = document.createEvent("SVGEvents");
            event.initEvent("click",true,true);
            nodelist._groups[0].item(i).dispatchEvent(event);
        }
    }
}
于 2020-09-22T08:34:05.547 回答