【问题标题】:D3.js SVG object not showing every time I run react project每次我运行反应项目时 D3.js SVG 对象都没有显示
【发布时间】:2021-12-31 23:57:11
【问题描述】:

我创建了一个基本的D3 svg 只是为了用反应测试一些东西。作为参考,这是我的代码:

App.js

import './App.css';
import Graph from './Graph/Graph';

function App() {
  return (
    <Graph />
  );
}

export default App;

Graph.js

import * as d3 from "d3"

function Graph(props) {
    let svg = d3.select("svg")

    svg.append('rect')
    .attr("height", 10)
    .attr("width", 10)
    .style("fill", "Green");
    
    return (
        <div>
            <svg id="svgID" width="640" height="480"></svg>
            <script src="https://d3js.org/d3.v5.min.js"></script>
            <script src="index.js"></script>
        </div>
    )
  }

export default Graph

我遇到的问题是它有时只加载绿色矩形,我似乎无法控制它何时加载以及何时不加载。

我认为这可能是因为 SVG 在它有时间附加任何内容之前被返回,但是,我不确定修复。有什么帮助吗?

【问题讨论】:

  • 你不能在不告诉 React 的情况下改变 DOM,你需要使用 useRef
  • @Jerboas86 你能进一步解释一下吗?
  • 为什么Graph 中有脚本标签?

标签: javascript reactjs d3.js


【解决方案1】:

您需要引用您的 svg DOM 元素,该元素在渲染之间持续存在。 React API 为您提供了 useRef 来使用功能组件 (see docs) 来做到这一点。

要将 DOM 元素与引用绑定,您需要使用 ref JSX arrtibute。

<svg ref={svgRef} id="svgID" width="640" height="480"></svg>

由于 useRef 不知道它何时与 DOM 元素绑定,因此您需要将返回的 "ref" 与 useEffect 挂钩以检查 current 何时与 svg DOM 元素绑定。

import React, { useRef, useEffect } from 'react'
import * as d3 from "d3"

function Graph(props) {
    const svgRef = useRef(null);

    useEffect(
        () => {
             // Check that svg element has been rendered
             if(svg.current) {
                 let svg = d3.select(svgRef.current)

                 svg.append('rect')
                 .attr("height", 10)
                 .attr("width", 10)
                 .style("fill", "Green");
            }
        }

},[svgRef.current])
    
    return (
        <div>
            <svg ref={svgRef} id="svgID" width="640" height="480"></svg>
        </div>
    )
  }

export default Graph

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 2017-03-18
    相关资源
    最近更新 更多