模拟对动态渲染的React元素的点击

问题描述

我正在创建一个地理游戏,您应该在该游戏中单击世界地图上的特定国家/地区-如果单击正确的国家/地区,则该国家/地区会更改颜色,并且游戏会显示一个要单击的新国家/地区。如果玩家不知道,他可以单击一个按钮,向他显示正确的答案。为此,我想模拟一个click事件,以便调用相同的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,如何实现?

下面是我之前看过的一些问题,这些问题也没有帮助。 Simulate click event on react element React Test Renderer Simulating Clicks on Elements Simulating click on react element

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)