我正在尝试将此图https://bl.ocks.org/scresawn/0e7e4cf9a0a459e59bacad492f73e139转换为反应组件。到目前为止,我没有在屏幕上渲染任何东西。如果有人可以查看并提出改进代码的建议,那就太好了。此外,我将从另一个组件向组件传递数据,而不是获取 CSV 文件。任何帮助将不胜感激。
class ScaleTime extends Component {
constructor(){
super();
this.state = {
data: []
};
};
componentDidMount() {
fetch(data)
.then( (response) => {
return response.json() })
.then( (json) => {
this.setState({data: json});
});
};
//What is happening here?
componentWillMount(){
d3.csv("phage-history.csv", function (error, data) {
svgEnter = svg.selectAll("rect")
.data(data)
.enter();
svgEnter.append("rect")
.attr("rx", 25)
.attr("x", function (d) {
x = xScale(new Date(d.start));
return x;
})
.attr("y", function(d, i) { return 400 - (d.count*30); })
.attr("width", 25)
.attr("height", 25)
.attr("fill", "green")
.attr("stroke-width", "1px")
.attr("stroke", "black")
.on("mouseover", function (d) {
rect = d3.select(this);
rect.transition()
.duration(500)
.attr("y", function(d, i) {
console.log(this);
var x = rect.x;
return 20; })
.transition()
.duration(500)
.attr("rx", 2)
.attr("width", 300)
.attr("height", 100)
.attr("fill", "skyblue");
tooltip.html(d.authors + "<br>" + d.description);
tooltip
.style("top", 30)
.style("left",function () {
console.log("x", x);
return d3.event.pageX;
})
setTimeout(function () {
tooltip.style("visibility", "visible");
}, 1500);
})
.on("mouseout", function (d) {
d3.select(this)
.transition()
.duration(500)
.attr("rx", 25)
.attr("width", 25)
.attr("height", 25)
.transition()
.duration(500)
.delay(500)
.attr("y", function(d, i) { return 400 - (d.count*30); })
.attr("fill", "green");
//tooltip.text(d.authors);
return tooltip.style("visibility", "hidden");
});
});
}//componentWillMount
componentDidUpdate() {
var tooltip = d3.select("body")
.append("div")
.style("font-size", "12px")
.style("width", 285)
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden");
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var xScale = d3.scaleTime()
.domain([new Date("January 1, 1940 00:00:00"), new Date("January 4, 1980 00:00:00")])
.range([20, 900]);
var xAxis = d3.axisBottom(xScale);
}
render() {
return (
<div className="ScaleTime">
<svg width="960" height="500" />
svg.append("g")
.attr("transform", "translate(0,450)")
.call(xAxis);
</div>
);
}
}