我们把上一篇博文里的架构再拿过来用。
第一步
清空src/App.js里的className为App里的内容和componentDidMount方法
初始src/App.js如下:
import React, { Component } from 'react';
import * as d3 from 'd3';
import './App.css';
class App extends Component {
componentDidMount () {
}
render() {
return (
<div className="App">
</div>
);
}
}
export default App;
第二步
编写componentDidMount方法
1) 添加svg
componentDidMount () {
const width = 300, height = 300; // 画布的宽高
let svg = d3.select('.App') // 选择文档中第一个class为App的元素
.append('svg') // 添加一个svg元素
.attr('width', width)
.attr('height', height);
}
2) 在svg中追加矩形
const dataset = [ 34, 23, 54, 73, 88, 4 ];
const rectHeight = 25;
svg.selectAll('rect')
.data(dataset)
.enter() // node比数据少时,通过enter来添加node
.append('rect') // 添加足够数量的矩形元素
.attr('y', (d, i) => i * (rectHeight + 2)) // y坐标
.attr('width', d => d) // 矩形宽
.attr('height', rectHeight); // 矩形高
现在的src/App.js
此时,你可以在页面中看到
方法解释:
data() 绑定数据
enter() Selection实例中node数量少于data数量,使用该方法添加足够的node
append() 添加node
attr() node添加属性
各方法返回:
给大家种草一个网站:https://vizhub.com/