【发布时间】:2019-06-21 20:15:06
【问题描述】:
使用 react 我绘制了一个 D3 散点图。当我尝试通过我在开始时初始化的svg 在图表上添加新线时,它可以工作,即使用 svg 中呈现的按钮和 onlick 函数时。
当我尝试使用父母的道具执行此操作时,添加线条的功能会被触发,但不会添加线条。我已经阅读了有关使用enter() 的其他帖子,但这不起作用。我认为错误的是我设置 div 结构以安装原始 SVG 的方式,因为我有一个类为 chart-container 的 div 和一个 id 为 chart 的 div,我在其中添加了 SVG。有没有人认为我在添加行时选择svg 的方式是错误的?我不明白为什么线条没有呈现在 D3 图表上。
import React, { useEffect, useLayoutEffect } from 'react';
import * as d3 from 'd3';
import './Chart.css';
const Chart = (props) => {
useEffect(() => {
drawChart(props.data)
}, [props.columnType]);
useLayoutEffect(() => {
if (showLines) {
addLines(props.data)
return
} else {
removeLines()
}
}, [props.showLines]);
const addLines = (data) => {
const x = d3.scaleLinear().range([0, width]);
const y = d3.scaleLinear().range([height, 0]);
const parsedData = parseData(data, columnType);
parsedData.forEach((dataSet, index) => {
const { points } = dataSet;
const line = d3.line()
.x((d) => x(d.x))
.y((d) => y(d.yhat));
// If I use this selection, I cannot add the lines
d3.select("svg").enter().append("path")
.datum(points)
.attr("class", `line`)
.attr("d", line);
});
}
const drawChart = (data) => {
..... // Other code not added (related to configuring the graph)
// If I use this SVG I can add the lines
const svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("id", "chart-svg")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
..... // other code not added (related to rendering the points using the data)
}
return (
<div className="chart-container">
<div id="chart"></div>
</div>
);
}
【问题讨论】:
-
您只能将
enter用于与data绑定数据的选择 -
仔细查看bl.ocks.org/mbostock/3808218 并确保您了解其中的每一点