react中使用d3
Data Driven Documents (D3.js) is a JavaScript library used to create visualizations of data using HTML, CSS, and SVG. It does this by binding data to the DOM (Document Object Model) and its elements and allowing them to transform when the data changes.
数据驱动文档(D3.js)是一个JavaScript库,用于使用HTML,CSS和SVG创建数据可视化。 它通过将数据绑定到DOM(文档对象模型)及其元素并允许它们在数据更改时进行转换来实现此目的。
For example, let’s say we want to create a pie chart of amounts of books in every genre in a library. We have some data which we update every time a librarian enters a new book. We store it in the application state, in a variable called “books”.
例如,假设我们要创建一个图书馆中每种流派的书籍数量的饼图。 每当图书馆员输入一本新书时,我们都会更新一些数据。 我们将其存储在应用程序状态下的变量“ books”中。
const [books, setBooks] = useState(initialBooks)
const initialBooks = [
{
name: "Harry Potter and the Philosophers Stone",
author: "J. K. Rowling",
genre: "fantasy"
},{
name: "The Pedagogy of Freedom",
author: "Bell hooks",
genre: "non-fiction"
},{
name: "Harry Potter and the Chamber of Secrets",
author: "J. K. Rowling",
genre: "fantasy"
},{
name: "Gilgamesh",
author: "Derrek Hines",
genre: "poetry"
}
]
Right now we could create a chart that has 50% of fantasy, 25% of non-fiction and 25% of poetry. When the librarian adds a new book to the database, the data changes, and your graft shifts. Let’s say we add “50 vegan dishes”.
现在,我们可以创建一个图表,其中包含50%的幻想,25%的非小说和25%的诗歌。 当图书管理员将一本新书添加到数据库中时,数据将发生更改,并且您的嫁接发生转移。 假设我们添加了“ 50种素食主义者”。
setBooks(books.concat(
{
name: "50 vegan dishes",
author: "Antti Leppänen",
genre: "non-fiction"
}
))
When this data changes, our D3 graph updates the DOM to match the new data. We now have 40% fantasy, 40% non-fiction, and 20% poetry. D3 makes manipulating the website DOM easy. This means that you can use it to create, update and delete elements in the page structure.
当此数据更改时,我们的D3图将更新DOM以匹配新数据。 现在,我们有40%的幻想,40%的非小说和20%的诗歌。 D3使操作网站DOM变得容易。 这意味着您可以使用它来创建,更新和删除页面结构中的元素。
If you want to follow along with this example, you can use Create React App to create a simple React web app. If React is still unfamiliar to you, you can check out this tutorial from the React documentation.
如果您想遵循此示例,可以使用Create React App创建一个简单的React Web应用程序。 如果您仍然不熟悉React,可以从React文档中查看本教程 。
Create a new app, called my-d4-app
npx create-react-app my-d3-app
. Change directory into the created folder by usingcd my-d3-app
.创建一个名为my-d4-app
npx create-react-app my-d3-app
。 使用cd my-d3-app
目录更改为创建的文件夹。Install D3 by running
npm install d3 --save
.通过运行
npm install d3 --save
。Import D3 to App.js by adding
import * as d3 from d3
. You need to use import * (“import everything”) since D3 has no default exported module.通过将
import * as d3 from d3
添加到App.js中,将D3导入到App.js中。 您需要使用import *(“全部导入”),因为D3没有默认的导出模块。