[英]d3 elements not showing in react
我正在使用 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,因为我们还没有走那么远。#container
元素,但是我们的选择代码不会重新运行,因为没有任何东西会触发组件重新渲染。您可能会考虑使用回调引用 - 这是一个最小的示例:
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可以很好地协同工作。 但即使单独使用其中之一,理解执行模型也有好处——代码何时运行,何时不运行。 将它们一起使用时,具有这种水平的理解更为重要,否则会发生难以排除故障的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.