【发布时间】: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。
提前感谢您的帮助。另外,如果上面有不相关的细节,我很抱歉——我是前端新手。
【问题讨论】: