为了能够使用 useRef 钩子选择 SVG 元素,我应该指定 d3.select() 哪种打字稿类型?

Log*_*nam 9 javascript d3.js typescript reactjs react-hooks

我尝试将正确的类型添加到我的 d3.select 语句中,以便设置 mySVG 变量。

\n
function App() {\n  const [mySVG, setMySVG] = useState<d3.Selection<d3.BaseType, unknown, HTMLElement, any>>()\n  const svgRef = useRef<SVGSVGElement | null>(null)\n\n  useEffect(() => {\n     setMySVG(d3.select(svgRef.current));\n     \n  }, [])\n\n  return (\n    <svg ref= {svgRef}>\n\n\n    </svg>\n  );\n}\n
Run Code Online (Sandbox Code Playgroud)\n

目前,我在代码中得到了下面的错误突出显示:

\n

setMySVG( d3.select(svgRef.current) );

\n
\n

选择指定的节点元素。

\n
\n
\n

第一个通用“GElement”指的是要选择的元素的类型。第二个通用“OldDatum”是指所选元素上的基准类型。当重新选择具有先前设置的已知基准类型的元素时,这非常有用。

\n
\n
\n

@param node \xe2\x80\x94 要选择的元素

\n
\n
\n

'Selection<SVGSVGElement | 类型的参数 null,unknown,null,undefined>' 不可分配给类型为 'SetStateAction<Selection<BaseType,unknown,HTMLElement,any> | 的参数 未定义>'。\n键入'选择<SVGSVGElement | null,unknown,null,undefined>' 不可分配给类型'Selection<BaseType,unknown,HTMLElement,any>'。

\n
\n
\n

'select(...).select(...).select(...).data' 的类型在这些类型之间不兼容。\n类型 '{ (): undefined[]; (数据:NewDatum [] |可迭代,键?:d3.ValueFn<any,NewDatum |未定义,导入(“/Users/logithangunaratnam/JavascriptProjects/practice_graph_creator/frontend/node_modules/@types/styled-components/node_modules/@types/反应/索引").ReactText> | 未定义): d3.Selection<...>; <Ne...' 不可分配给类型 '{ (): undefined[]; (数据:NewDatum [] |可迭代,键?:d3.ValueFn<any,NewDatum |未定义,导入(“/Users/logithangunaratnam/JavascriptProjects/practice_graph_creator/frontend/node_modules/@types/styled-components/node_modules/@types/反应/索引").ReactText> | 未定义): d3.Selection<...>; <桀……'。存在具有此名称的两种不同类型,但它们不相关。\n参数“data”和“data”的类型不兼容。\n每个签名的“this”类型不兼容。\n类型“null”不能分配给类型“ HTMLElement'.

\n
\n

我已经通过将类型替换为 any 来使其工作,但我希望能够分配正确的关联类型。

\n

小智 0

要使用 D3 选择 SVG 元素并为“mySVG”分配正确的 TypeScript 类型,您可以对代码进行以下修改:

  1. 从 D3 导入必要的类型(“Selection”和“BaseType”)
  2. 更新“mySVG”的状态定义以允许“null”值作为初始状态,并指定正确的类型。
  3. 在“useEffect”中,在尝试使用 D3 选择“svgRef.current”之前检查“svgRef.current”是否不为空。这有助于防止空引用错误。

import { Selection, BaseType } from 'd3';

function App() {
  const [mySVG, setMySVG] = useState<Selection<SVGSVGElement | null, unknown, HTMLElement, any> | null>(null);
  const svgRef = useRef<SVGSVGElement | null>(null);

  useEffect(() => {
    if (svgRef.current) {
      setMySVG(d3.select<SVGSVGElement, unknown>(svgRef.current));
    }
  }, []);

  return (
    <svg ref={svgRef}>
      {/* Your SVG content here */}
    </svg>
  );
}
Run Code Online (Sandbox Code Playgroud)