【问题标题】:Stacked Bar graph with ReactJS使用 ReactJS 的堆积条形图
【发布时间】:2020-12-01 18:30:46
【问题描述】:

我必须做一个从 API 获取数据的堆叠条形图,但我发现了一些问题。

1- 一方面,我得到的数据不是四舍五入的,即使我使用 %。

2- 另一方面,我得到的总和并不总是 100%,然后条形有时比预期短几个像素,有时比预期长几个像素。

import styled from 'styled-components'
import { Data } from '../../Types'

const Colors: Record<string, string> = {
    warning: 'yellow',
    good: 'green',
    danger: 'red',
}

const StackedBar = (props: {
    title?: string
    Data: Data | null
}) => {

    return (
        <div>
            <div
                style={{
                    display: 'flex',
                    flex: '1 1 auto',
                    alignSelf: 'auto',
                }}
            >
                {props && props.Data ? (
                    props.Data.items.map((item) => {
                        const percentage =
                            (item.count / items_total) * 100
                        return (
                            <Rectangle
                                percentage={percentage}
                                color={
                                    itemColors[item.items_total]
                                }
                            />
                        )
                    })
                ) : (
                    <Rectangle percentage={100} color="grey" />
                )}
            </div>
        </div>
    )
}

export default StackedBar

const Rectangle = styled.div<{ percentage: number; color: string }>`
    height: 20px;
    width: ${(props) => props.percentage}%;
    background-color: ${(props) => props.color};
`

const NormalBold = styled.p`
    font-weight: 700;
    font-size: var(--font-size-normal);
`

【问题讨论】:

    标签: javascript reactjs graph graphics bar-chart


    【解决方案1】:

    percentage =(item.count / items_total) * 100,这里items_total没有定义,再次查看代码。我认为应该是 item.items_total。 四舍五入使用 Math.round(percentage) 对值进行四舍五入。 我认为这应该可以解决您的问题。

    【讨论】:

    • 嗨!谢谢,我在其他地方定义了 items_total(这是来自 API 的调用)。我怎样才能使用 Math.round 不超过或不低于 100%?
    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 2017-11-02
    • 1970-01-01
    • 2014-02-09
    • 2020-09-14
    相关资源
    最近更新 更多