我正在尝试使用React,d3和Typescript渲染Axis。我将显示代码并指出问题。
class Axis extends React.Component<{}> {
private ref: React.RefObject<SVGGElement>;
constructor(props: any) {
super(props);
this.ref = React.createRef();
}
public componentDidMount() {
this.renderAxis();
}
public componentDidUpdate() {
this.renderAxis();
}
public render() {
return (
<g transform="translate(10,30)" ref={this.ref} />
)
}
private renderAxis = () => {
const scale = d3.scaleLinear().domain([0, 10]).range([0, 200]);
const axis = d3.axisBottom(scale);
d3**.select(this.ref)**.call(axis);
}
}
export default Axis;
我创建了一个应包含轴的SVG g 元素。因此,我创建了一个引用,以便以后可以访问该元素。
private ref: React.RefObject<SVGGElement>;
<g transform="translate(10,30)" ref={this.ref} />
当我尝试在此处选择此元素时...
d3.select(this.ref).call(axis);
...我在 this.ref 上收到错误:无法将类型'RefObject'的参数分配给类型'BaseType'的参数
我不知道该怎么办。有人能指出我正确的方向吗?
已解决
好吧,我现在觉得很蠢。我错误地访问了裁判。 应该是 this.ref .current