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を使用するかどうかにかかわらず、どうすればこれを達成できますか?

以下は、私が見たいくつかの以前の質問で、これも役に立ちませんでした。 React要素でクリック イベントをシミュレートする React Test Renderer要素でクリックをシミュレートする React 要素でクリックをシミュレート する

4

1 に答える 1