【问题标题】:Simulating a click on dynamically rendered React element模拟点击动态渲染的 React 元素
【发布时间】:2021-01-07 09:22:33
【问题描述】:

我正在创建一个地理游戏,您应该点击世界地图上的特定国家 - 如果您点击右边的国家,该国家会改变颜色,并且游戏会显示一个可供点击的新国家。如果玩家不知道,他可以点击一个按钮,它会告诉他正确的答案。为此,我想模拟一个点击事件,以便调用相同的 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

【问题讨论】:

    标签: javascript reactjs d3.js onclick use-ref


    【解决方案1】:

    我终于解决了——我没有调用在节点内设置的 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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-05
      • 1970-01-01
      • 2020-10-09
      • 2020-10-28
      • 2020-07-18
      • 2021-01-30
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      相关资源
      最近更新 更多