【问题标题】:How can I use d3.js to mutate svg in a variable instead of from the DOM如何使用 d3.js 在变量中而不是从 DOM 中改变 svg
【发布时间】:2021-02-08 10:16:48
【问题描述】:

我将一个 react 组件嵌入到 MDX 文档中,如下所示:

// index.mdx

import MyComponent from './diagram'
const src = `
graph TD;
  A[foo] --> B[bar]
`

Behold! a Mermaid diagram:
<MyComponent id="diag" content={src}/>

组件如下所示:

// diagram.js

class FooDiag extends Component {

  // code that populates this.state.svg goes here

  render() {
    if (!this.state.svg) {
      return <div>Loading...</div>
    }

    // confirms that the root of the svg has id="diag"
    console.log(this.state.svg)

    // doesn't work
    // var modifedSvg = d3.select("#diag").append("circle")
    //      .attr("cx", 10)
    //      .attr("cy", 10)
    //      .attr("r", 5)
    //      .attr("fill", "red")
    //
    // return <div dangerouslySetInnerHTML={{ __html: modifiedSvg }} />

    return <div dangerouslySetInnerHTML={{ __html: this.state.svg }} />
  }

(我得到了上面here的模式)

我的目标是使用Mermaid 生成svg,然后使用d3 对其进行修改,然后再将其显示在页面上。上面的代码有效:图表确实显示在页面上。

但我只知道如何让 d3 从 DOM 中选择。我认为我上面注释代码的问题是this.state.svg 还不是 DOM 的一部分,所以 d3 找不到它。我想有一种方法可以从变量中获取 svg,但是 d3 是一个很大的地方,我不知道要搜索什么。

我怎样才能使上面我的 sn-p 中的注释 d3 代码在我的图表中放置红色圆圈?

我试过了:

var d3svg = d3.select("#diag").html(this.state.svg)
d3svg.append("circle")
  .attr("cx", 10)
  .attr("cy", 10)
  .attr("r", 5)
  .attr("fill", "red")
// console.log(d3svg.???)

我不知道它是否有效。我不知道,因为我不知道如何从 d3svg 选择对象中获取实际的 svg。

提前感谢您的帮助。另外,如果上面有不相关的细节,我很抱歉——我是前端新手。

【问题讨论】:

    标签: reactjs svg d3.js


    【解决方案1】:

    #diag 选择给了我一些除了顶级svg 元素之外的东西,这使得将该元素作为字符串取回变得很棘手。选择 svg 只会给我那个元素。

    这成功了:

    var d3svg = d3.select("svg").html(this.state.svg)
    d3svg.select("g[id^='flowchart-A']").append("circle")
       .attr("cx", 10)
       .attr("cy", 10)
       .attr("r", 5)
       .attr("fill", "red")
    
    return <div dangerouslySetInnerHTML={{ __html: d3svg.node().innerHTML }} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2018-12-13
      • 2020-11-24
      • 2019-10-26
      相关资源
      最近更新 更多