import React, { ForwardedRef, forwardRef, useImperativeHandle, useState, useMemo } from "react"; import "./index.less"; const getTwoPointDistance = (pointOne, pointTwo) => { const minusX = Math.abs(pointOne[0] - pointTwo[0]); const minusY = Math.abs(pointOne[1] - pointTwo[1]); return Math.sqrt(minusX * minusX + minusY * minusY); } const getPolylineLength = (points) => { const lineSegments = new Array(points.length - 1).fill(0).map((_, i) => [points[i], points[i + 1]]); const lengths = lineSegments.map((item) => getTwoPointDistance(item[0], item[1])); return lengths.reduce((all, num) => all + num, 0); } 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 = () => { let line1Points = [ [0, height * 0.2], [width * 0.18, height * 0.2], [width * 0.2, height * 0.4], [width * 0.25, height * 0.4], [width * 0.27, height * 0.6], [width * 0.72, height * 0.6], [width * 0.75, height * 0.4], [width * 0.8, height * 0.4], [width * 0.82, height * 0.2], [width, height * 0.2] ]; let line2Points = [[width * 0.3, height * 0.8], [width * 0.7, height * 0.8]]; const line1Length = getPolylineLength(line1Points); const line2Length = getPolylineLength(line2Points); return { line1Points: line1Points.map(point => point.join(',')).join(' '), line2Points: line2Points.map(point => point.join(',')).join(' '), line1Length, line2Length }; } const { line1Points, line2Points, line1Length, line2Length } = useMemo( calcSVGData, [width, height] ); return
; }); export default Index;