[英]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.