【发布时间】:2017-12-07 17:28:24
【问题描述】:
我正在尝试使用 React 在 D3.js 上为我的折线图添加标签。我已经编写了下面的代码,它将显示轴,但文本节点不可见,但我可以在开发人员工具的 DOM 中看到它。
import React, { PropTypes, Component } from 'react';
import * as d3 from 'd3';
export default class Axis extends Component {
static propTypes= {
h: PropTypes.number.isRequired,
axis: PropTypes.func.isRequired,
axisType: PropTypes.oneOf(['x', 'y']).isRequired,
}
componentDidMount = () => { this.renderAxis(); }
componentDidUpdate = () => { this.renderAxis(); }
renderAxis = () => {
const node = this.axisRef;
d3.select(node).call(this.props.axis);
// const domain = d3.selectAll('path.domain');
const ticks = d3.selectAll('g.tick');
ticks.select('text').style('font-family', 'Poppins');
ticks.select('text').style('fill', 'black');
}
render() {
const translate = `translate(0,${(this.props.h)})`;
return (
<g
ref={(node) => { this.axisRef = node; }}
className="axis"
transform={this.props.axisType === 'x' ? translate : ''}
>
<text value={this.props.axisType === 'x' ? 'x axis' : 'y axis'}>Hello world</text>
</g>
);
}
}
【问题讨论】:
-
你能把它上传到 jsfiddle 上吗? (并小心处理依赖)
-
根 SVG 和/或父 SVG 元素的尺寸是多少?可能想检查一下。
-
@LouisLecocq 我没有 js fiddle,但有我放在一起的代码 pen.io。我刚刚将图表标签放入 JSX 并使用 CSS 定位,如果有更好的解决方案请发布。 lineChartWithLabels.