d3.select()不返回任何东西



我是React的新手,尤其是d3。我试着用一个自定义字典写一个d3比例图。所有东西都显示出来了,除了最后一节,我用了d3。选择此选项可向我的图形添加一个轴标签。我的render()方法返回绘制图形生成的html,如下所示。

render(){
return this.drawGraph();
}
drawGraph(){
return(
<svg viewBox={`0 0 ${this.width} ${this.height}`} style={{maxWidth: `${this.width}px`, font: "10px sans-serif"}}>
<g fill="steelblue">
${this.fruits.map(d =>
<svg key={d.name}>
<rect y={this.y(d.name)} x={this.x(0)} width={this.x(d.count) - this.x(0)} height={this.y.bandwidth()}></rect>
</svg>)}
</g>
<g fill="white" textAnchor="end" transform={`translate(-6,${this.y.bandwidth()/2})`}>
${this.fruits.map(d =>
<svg key={d.name}>
<text y={this.y(d.name)} x={this.x(d.count)} dy="0.35em">{d.count}</text>
</svg>)}
</g>
<g transform={`translate(0, ${this.margin.top})`}>
{d3.select('g')
.call(d3.axisLeft(this.y))
.call(g => g.select(".domain").remove())
.node()}
</g>
</svg>    
);
}

谁能告诉我为什么d3.select()子句返回为空?为什么它找不到它所在的块,我怎么解决这个问题?

g标签内调用d3.select(‘g’)。这就是为什么它是空的。试着在componentDidMount()(用于组件)或useEffecthook(用于函数)中调用它。

最新更新