const chart = useRef<Chart null>(null); return <> <Box ref={ref} id={chart-${uniqueId}}…
- User
const chart = useRef<Chart|null>(null); return <> <Box ref={ref} id={
chart-${uniqueId}} width={!showToolbar ? "calc(100% - 5px)" : "calc(100% - 55px)"} height="100%" position="relative" sx={{borderLeft: theme =>2px solid ${theme.palette.grey[50]}}} > };export default CandleChartToolbar;
import React, {useEffect} from "react"; import {registerOverlay} from "klinecharts"; import {Icon, IconButton, useTheme} from "@mui/material"; import { RulerIcon } from "../../icons";
const CustomOverlay = ({chart, price, paneId}: any) => { const customizeChart = () => { registerOverlay({ name: "customOverlay", needDefaultXAxisFigure: true, totalStep: 1, createPointFigures: function({overlay, coordinates}) { const y = chart.current?.convertToPixel(overlay.points) console.log(y);
codereturn [ { type: "line", attrs: { coordinates: [ {x: 0, y: 150}, {x: 1000, y: 150}, ], }, styles: { style: "solid", color: "#1e293b", }, }, { type: "rect", attrs: { x: coordinates[0].x - 100, y: coordinates[0].y - 25, width: 100, height: 24, }, styles: { style: "fill", color: "#1e293b3d", }, }, ]; }, });};
const onClickHandler = () => { chart.current?.createOverlay({ name: "customOverlay", styles: { rect: { color: "#1e293b3d", }, text: { color: "#1e293b", }, line: { color: "#1e293b", }, point: { color: "#1e293b", borderColor: "#1e293b", activeColor: "#1e293b", activeBorderColor: "#1e293bd1", }, }, points: [{ dataIndex: 74, timestamp: 0, value: price, }], onSelected: function(event) { console.log(event.overlay.id);
codereturn false; }, });};
useEffect(() => { customizeChart(); }, []);
return <> <IconButton onClick={onClickHandler} sx={{borderRadius: 2, color: "#677294"}}> </>; };
export default CustomOverlay;
TypeError: Cannot read properties of undefined (reading 'paneId')
15 | const y = chart.current?.convertToPixel(overlay.points)
в чем ошибка и как исправить
- Assistant
Ошибка возникает из-за того, что переменная
chartв компонентеCustomOverlayне определена или равнаnull.Для исправления ошибки, можно добавить проверку на существование переменной
chartперед ее использованием.Вместо строки:
javascriptconst y = chart.current?.convertToPixel(overlay.points);Вы можете использовать следующий код:
javascriptconst y = chart?.current?.convertToPixel(overlay.points);Таким образом, вызов
convertToPixelбудет выполнен только в случае, еслиchartсуществует и не равенnull. Это предотвратит ошибку при попытке чтения свойстваconvertToPixelна неопределенной переменнойchart.