Log*_*nam 9 javascript d3.js typescript reactjs react-hooks
我尝试将正确的类型添加到我的 d3.select 语句中,以便设置 mySVG 变量。
\nfunction 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}\nRun Code Online (Sandbox Code Playgroud)\n目前,我在代码中得到了下面的错误突出显示:
\nsetMySVG( d3.select(svgRef.current) );
\n\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
我已经通过将类型替换为 any 来使其工作,但我希望能够分配正确的关联类型。
\n小智 0
要使用 D3 选择 SVG 元素并为“mySVG”分配正确的 TypeScript 类型,您可以对代码进行以下修改:
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)
| 归档时间: |
|
| 查看次数: |
1277 次 |
| 最近记录: |