未显示的d3元素发生反应



我使用的是react with d3js,但由于某种原因,d3容器div没有呈现。我怀疑在选择本地div时有些地方做得不正确,但我不知道是什么。

index.html&index.js文件只是普通的样板代码,唯一的修改是在下面发布的App.jsx文件中

import React from "react";
import * as d3 from "d3";
function App() {
const data = [
{ name: "A", score: 70 },
{ name: "B", score: 90 },
{ name: "C", score: 50 }
];
const width = 800;
const height = 800;
const margin = { top: 50, bottom: 50, left: 50, right: 50 };
const svg = d3
.select("#container")
.append("svg")
.attr("width", width - margin.left - margin.right)
.attr("height", height - margin.top - margin.bottom)
.attr("viewbox", [0, 0, width, height]);
const x = d3
.scaleBand()
.domain(d3.range(data.length))
.range([margin.left, width - margin.right])
.padding(0.1);
const y = d3
.scaleLinear()
.domain([0, 100])
.range([height - margin.bottom, margin.top]);
svg
.append("g")
.attr("fill", "royalblue")
.selectAll("rect")
.data(data.sort((a, b) => d3.descending(a.score, b.score)))
.join("rect")
.attr("x", (d, i) => x(i))
.attr("y", (d) => y(d.score))
.attr("width", x.bandwidth())
.attr("height", (d) => y(0) - y(d.score));
svg.node();
return (
<div>
<h1>Chart</h1>
<div id="container"></div>
</div>
);
}
export default App;

在代码运行时思考世界的状态:

  • App组件在页面加载时呈现
  • 我们调用d3.select('#container'),但什么也没发生。页面上没有具有该ID的div,因为我们还没有走那么远
  • D3操作仍在继续,可能不会出现任何错误,因为在设计上,D3允许您对空的选择进行操作
  • 我们返回一个JSX值,描述我们希望React渲染的DOM。在我们返回此消息后不久的某个时间,元素被呈现到页面中
  • 现在我们有了#container元素,但我们的选择代码不会重新运行,因为没有任何东西会触发组件重新渲染

您可以考虑使用回调ref-这里有一个最小的例子:

const doD3Stuff = (element) => {
const width = 800;
const height = 800;
const margin = { top: 50, bottom: 50, left: 50, right: 50 };
const svg = d3
// the select method can accept an actual element instead of a selector
.select(element)
.append("svg");
// etc.
};
const App = () => {
return (
<div>
<h1>Chart</h1>
<div id="container" ref={doD3Stuff} />
</div>
);
};

这是一个起点,但它当然不会涉及当数据发生变化时会发生什么,并且你想要重新绘制、动画等。

React和D3可以很好地配合使用。但是,即使只单独使用其中一个,了解执行模型也是很好的——代码何时运行,何时不运行。当将它们一起使用时,更重要的是要有这样的理解水平,否则会发生难以排除故障的事情。

最新更新