按照示例页面尝试设置react + d3,我看到一个空白页面呈现。该指南位于https://dzone.com/articles/how-you-can-translate-any-random-d3-example-to-rea
完整的组件代码(虽然主要是复制+粘贴):
import React, {Component} from 'react';
import * as topojson from 'topojson';
import * as d3 from 'd3';
class CongressionalDistricts extends Component {
state = {
usData: null,
usCongress: null
}
componentWillMount() {
// load data
d3.queue()
.defer(d3.json, "https://raw.githubusercontent.com/Swizec/113th-congressional-districts/master/public/us.json")
.defer(d3.json, "https://raw.githubusercontent.com/Swizec/113th-congressional-districts/master/public/us-congress-113.json")
.await((error, usData, usCongress) => {
this.setState({
usData,
usCongress
})
})
}
componentDidUpdate() {
// render example D3
const svg = d3.select(this.refs.anchor)
// const {width, height} = this.props;
const width = 960;
const height = 600;
const projection = d3.geoAlbers()
.scale(1280)
.translate([width / 2, height / 2]);
// console.log(projection);
const path = d3.geoPath(projection);
console.log('path');
// console.log(path);
const us = this.state.usData
const congress = this.state.usCongress;
console.log(topojson.feature(us, us.objects.land));
console.log(us);
console.log(congress);
svg.append("defs").append("path")
.attr("id", "land")
.datum(topojson.feature(us, us.objects.land))
.attr("d", path);
svg.append("clipPath")
.attr("id", "clip-land")
.append("use")
.attr("xlink:href", "#land");
svg.append("g")
.attr("class", "districts")
.attr("clip-path", "url(#clip-land)")
.selectAll("path")
.data(topojson.feature(congress, congress.objects.districts).features)
.enter().append("path")
.attr("d", path)
.append("title")
.text(function (d) {
return d.id;
});
svg.append("path")
.attr("class", "district-boundaries")
.datum(topojson.mesh(congress, congress.objects.districts, function (a, b) {
return a !== b && (a.id / 1000 | 0) === (b.id / 1000 | 0);
}))
.attr("d", path);
svg.append("path")
.attr("class", "state-boundaries")
.datum(topojson.mesh(us, us.objects.states, function (a, b) {
return a !== b;
}))
.attr("d", path);
}
render() {
const {usData, usCongress} = this.state;
if (!usData || !usCongress) {
return null;
}
return <g ref="anchor"/>;
}
}
检查控制台时我看到警告:
此浏览器中无法识别该标记。如果你打算渲染一个 React组件,以大写字母开头。
以及在0x0元素中可用。我尝试过硬编码以及从传递道具的父组件内渲染,但仍然看到现在的图表。我有什么想法吗?