import React, { ForwardedRef, forwardRef, useImperativeHandle, useState, useMemo } from "react"; import "./index.less"; const svgWH = [300, 35]; const rowNum = 1; const rowPoints = 40; const rectWidth = 7; const halfRectWidth = rectWidth / 2; const getPoints = () => { const [w, h] = svgWH; const horizontalGap = w / (rowPoints + 1); const verticalGap = h / (rowNum + 1); let points = new Array(rowNum) .fill(0) .map((_, i) => new Array(rowPoints) .fill(0) .map((_, j) => [horizontalGap * (j + 1), verticalGap * (i + 1)]) ); return points.reduce((all, item) => [...all, ...item], []); } const getData = () => { const h = svgWH[1]; const heights = new Array(rowNum * rowPoints) .fill(0) .map(() => Math.random() > 0.8 ? Math.random() * (h - 0.7 * h + 1) + 0.7 * h : Math.random() * (0.5 * h - 0.2 * h + 1) + 0.2 * h ); const minHeights = new Array(rowNum * rowPoints) .fill(0) .map((_, i) => heights[i] * Math.random()); const randoms = new Array(rowNum * rowPoints) .fill(0) .map(() => Math.random() + 1.5); return { heights, minHeights, randoms }; } interface ComponentStyle { mainColor?: string; subColor?: string; } export interface ComponentProps { style?: ComponentStyle; base?: { width?: number, height?: number } } export interface ComponentRef { updateConfig: (config: ComponentProps) => void; } const Index = forwardRef((props: ComponentProps, ref: ForwardedRef) => { const { style: defStyle, base: defBase } = props; const [style, setStyle] = useState({ ...defStyle }); const [width, setWidth] = useState(defBase?.width || 300); const [height, setHeight] = useState(defBase?.height || 100); const { mainColor = "#83BFF6", subColor = "#00CED1" } = style || {}; useImperativeHandle(ref, () => ({ updateConfig: (newConfig) => { setStyle({ ...newConfig.style }); setWidth(newConfig.base.width); setHeight(newConfig.base.height); }, })); const calcSVGData = () => ({ ...getData(), points: getPoints(), svgScale: [width / svgWH[0], height / svgWH[1]] }) const { points, heights, minHeights, randoms, svgScale } = useMemo(calcSVGData, [width, height]); return
{points.map((point, i) => ( 0.5 ? mainColor : subColor} x={point[0] - halfRectWidth} y={point[1] - heights[i] / 2} width={rectWidth} height={heights[i]} > ))}
; }); export default Index;