簡體   English   中英

堆積條形圖 ReactJS

[英]Stacked Bar graph with ReactJS

我必須做一個單一的堆疊條形圖從 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);
`

percentage =(item.count / items_total) * 100 ,這里items_total沒有定義,再檢查代碼。 我覺得應該是item.items_total。 舍入使用 Math.round(percentage) 舍入值。 我認為這應該可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM