繁体   English   中英

React、Typescript、d3js、获取无重载匹配此调用

[英]React, Typescript, d3js, Getting a No overload matches this call

我发现在使用 d3js 的 scaleLinear() 函数时,Typescript 抛出了一个错误,想知道是否有人可以指出我解决这个问题的方向。 该代码内置于 react 中,并使用了 typescript。 这是源代码:

import React, { useRef, useState, useEffect } from 'react';
import { select, Selection } from 'd3-selection';
import { scaleLinear } from 'd3-scale';

const dataTest = [
    {
        name: 'Oct30',
        number: 8000
    },
    {
        name: 'Oct29',
        number: 2000
    },
    {
        name: 'Oct28',
        number: 600
    },
    {
        name: 'Oct27',
        number: 3005
    }
]

const Barchart: React.FC = () => {

    const ref = useRef<SVGSVGElement | null>(null);
    const [selection, setSelection] = useState< null | Selection<SVGSVGElement | null, unknown, null, undefined>>(null);

    const y = scaleLinear()
        .domain([0, 10000])
        .range([0, 400])
    
    useEffect(() => {
        if(!selection){
            setSelection(select(ref.current))
        } else {

            console.log("y(0) ", y(0));
            console.log("y(0) ", y(2305));  // What happens as a test

// selection is where typescript is showing the error
            selection 
                .selectAll('rect')
                .data(dataTest)
                .enter()
                .append('rect')
                .attr('width', 100)
                .attr('x', (_, i) => i * 100)
                .attr('fill', 'orange')
                .attr('height', d => y(d.number)); // <the y() seems to be the problem.
        }
    }, [selection])
    return (
        <div> 
                <svg ref={ref} width={800} height={400} />
        </div>
    );
};


}
export default Barchart;

这是打字稿错误:

给定域中的值,返回范围内的相应值,如果有插值,则进行插值。 如果给定值在域之外,并且未启用钳位,则可以外推映射以使得返回值在范围之外。 注意:作为插值的一部分,比例尺应用的插值函数可能会改变范围类型的输出类型。 @param value — 域中的数值。

继续:

没有重载匹配这个调用。 重载 1 of 4, '(name: string, value: null): Selection<SVGRectElement, { name: string; 数量:数量; }, SVGSVGElement | null,unknown>',给出了以下错误。 '(this: SVGRectElement, d: { name: string; number: number; }) => number | 类型的参数 undefined' 不能分配给类型为 'null' 的参数。 重载 2 of 4, '(name: string, value: string | number | boolean): Selection<SVGRectElement, { name: string; 数量:数量; }, SVGSVGElement | null,unknown>',给出了以下错误。

我试图改变:

.attr('height', d => y(d.number))

.attr('height', d => d.number)

没有错误。 我的猜测是在这一行“const y = scaleLinear()”我需要设置一些东西。 任何帮助,将不胜感激。

没有运气做出这个改变:

    let y = scaleLinear<number>()
        .domain([0, 10000])
        .range([0, 400])

问题是scaleLinear()不会在 100% 的时间内返回值。 ScaleLinear类型的定义中,您可以看到它可以返回numberundefined

const y: ScaleLinear
(value: NumberValue) => number | undefined

但是当你在你的 SVG 选择上设置属性 'height' 时,你设置的值必须是一个number 它不能是undefined

修复很容易。 如果y(d.number)返回undefined我们会提供一个备用number作为高度。 这里我使用的是 0。

.attr('height', d => y(d.number) || 0 );

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM