const ScreenerCharts = () => { const symbol = useSelector((state: AppState) =>…
- User
const ScreenerCharts = () => { const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const [windowsChart, setWindowsChart] = useState<"one" | "twoVertical" | "twoHorizontal" | "for">("for"); const [intervalFirstChart, setIntervalFirstChart] = useState("5m"); const [intervalSecondChart, setIntervalSecondChart] = useState("1h"); const [intervalThirdChart, setIntervalThirdChart] = useState("4h"); const [intervalFourthChart, setIntervalFourthChart] = useState("1d"); return ( <IconButton onClick={() => setWindowsChart("one")} sx={{m: .3, height: 23, width: 23}}><ChartOneWindowIcon sx={{fill: windowsChart === "one" ? "#B41C18" : "#d4d4d4"}} /> <IconButton onClick={() => setWindowsChart("twoVertical")} sx={{m: .3, height: 23, width: 23}}><ChartTwoVerticalWindowsIcon sx={{fill: windowsChart === "twoVertical" ? "#B41C18" : "#d4d4d4"}} /> <IconButton onClick={() => setWindowsChart("twoHorizontal")} sx={{m: .3, height: 23, width: 23}}><ChartTwoHorizontalWindowsIcon sx={{fill: windowsChart === "twoHorizontal" ? "#B41C18" : "#d4d4d4"}} /> <IconButton onClick={() => setWindowsChart("for")} sx={{m: .3, height: 23, width: 23}}><ChartForWindowsIcon sx={{fill: windowsChart === "for" ? "#B41C18" : "#d4d4d4"}} /> { windowsChart === "one" ? : windowsChart === "twoVertical" ? <> </> : windowsChart === "twoHorizontal" ? <> </> : <> </> } ); };
export default ScreenerCharts;
const ChartInterval: React.FC = ({symbol, windowChart, interval, handleIntervalChange}) => ( <Box height="100%" p={0.5} width="calc(100% - 4px)" borderRadius="8px" sx={{bgcolor: "#fff"}}> <FormControl sx={{mb: 1, "& .MuiSelect-select": {paddingY: 1}, "& fieldset": {border: "none"}, height: 31, backgroundColor: "#eeeeee", color: "#191919", padding: "0", borderRadius: "8px", }}> <Select sx={{fontSize: "12px"}} value={interval} onChange={(e) => handleIntervalChange(e, windowChart)}> 1м 5м 15м 1ч 4ч 1д 1н { symbol ? : Выберите монету } );
const KLineChart: React.FC = React.memo(({symbol, interval, windowChart}) => { const [candlesticks, setCandlesticks] = useState<KLineData[]>([]); const fetchCandlesticks = () => { setWaiting(true); fetchSymbolsKlines(symbol, interval) .then((data) => { if (undefined === data) return;
setCandlesticks(data.map(item => ({ timestamp: dayjs.utc(item[0]).valueOf(), open: parseFloat(item[1].toString()), high: parseFloat(item[2].toString()), low: parseFloat(item[3].toString()), close: parseFloat(item[4].toString()), volume: parseFloat(item[5].toString()), }))); }) .finally(() => { setWaiting(false); });};
useEffect(() => { fetchCandlesticks(); }, [symbol, interval]);
return ( <CandleChart candles={candlesticks} tradeId={
chart${windowChart}-${symbol}-${interval}} symbolName={symbol} chartInterval={interval} /> ); });export const CandleChart = ({ candles, tradeId, symbolName, chartInterval, }: CandleChartProps) => { const chart = useRef<Chart|null>(); const paneId = useRef(""); const [figureId, setFigureId] = useState(""); const ref = useRef(null); useEffect(() => { chart.current = init(
chart-${tradeId}, {styles: chartStyles});return () => dispose(`chart-${tradeId}`);}, [tradeId]);
const removeFigure = () => { chart.current?.removeOverlay({ id: figureId, }); setFigureId(""); };
console.log(tradeId, figureId);
return (<><Stack direction="row" height={height && !handle.active ? 550 : "100%" || "calc(100% - 140px)"} width="100%"> <Box ref={ref} id={
chart-${tradeId}} width="calc(100% - 55px)" height={"100%"} sx={{borderLeft: "2px solid #F5F5F5"}} > { figureId.length > 0 && <Stack sx={{ backgroundColor: "#CBD4E3", borderRadius: 1, position: "absolute", zIndex: 10, right: 80, top: 30, border: "2px solid #F5F5F5", }} spacing={2} > <IconButton sx={{borderRadius: 1}} onClick={removeFigure}> } </>); });const CandleChartToolbar = ({chart, paneId, setFigureId, handle}: CandleChartToolbarProps) => { const removeOverlay = () => { chart.current?.removeOverlay(); setFigureId(""); };
const fullScreenHandle = () => { if(handle.active) { handle.exit(); } else { handle.enter(); } };
return <> <Stack className="scroll-block" direction="column" alignItems="center" spacing={1} sx={{ width: "55px", height: "100%", overflowY: "scroll", }} >
<IconButton sx={{borderRadius: 2}} style={{height: 40}} onClick={fullScreenHandle}> <Icon component={FullScreenIcon} sx={{height: 18}} /> </IconButton> <IconButton sx={{borderRadius: 2}} onClick={removeOverlay}> <Icon component={BasketIcon}/> </IconButton> </Stack></>; };
export default CandleChartToolbar;
const PriceLineTool = ({chart, paneId, setFigureId}: ToolProps) => { const onClickHandler = () => { chart.current?.createOverlay({ name: "priceLine", styles: { text: { color: "#1e293b", }, line: { color: "#1e293b", }, point: { color: "#1e293b", borderColor: "#1e293b", activeColor: "#1e293b", activeBorderColor: "#1e293bd1", }, }, onSelected: function(event) { setFigureId(event.overlay.id);
return false; }, onDeselected: function() { setFigureId(""); return false; }, });};
return <> <IconButton onClick={onClickHandler} sx={{borderRadius: 2}}> </>; };
export default PriceLineTool;
import {ToolProps} from "./Tool.props"; import {Icon, IconButton} from "@mui/material"; import React, {useEffect} from "react"; import {RectIcon} from "../../../icons"; import {registerOverlay} from "klinecharts";
const RectTool = ({chart, paneId, setFigureId}: ToolProps) => { useEffect(() => { registerOverlay({ name: "rect", needDefaultPointFigure: true, needDefaultXAxisFigure: true, needDefaultYAxisFigure: true, totalStep: 3, onSelected: function(event) { setFigureId(event.overlay.id);
return false; }, onDeselected: function() { setFigureId(""); return false; }, createPointFigures: function({coordinates}) { if (coordinates.length === 2) { const xDis = coordinates[1].x - coordinates[0].x; const yDis = coordinates[1].y - coordinates[0].y; return { key: "rect", type: "rect", attrs: { x: coordinates[0].x, y: coordinates[0].y, width: xDis, height: yDis, }, }; } return []; }, });}, []);
const onClickHandler = () => { chart.current?.createOverlay({ name: "rect", styles: { rect: { color: "#1e293b3d", }, line: { color: "#1e293b", }, point: { color: "#1e293b", borderColor: "#1e293b", activeColor: "#1e293b", activeBorderColor: "#1e293bd1", }, }, }); };
return <> <IconButton onClick={onClickHandler} sx={{borderRadius: 2}}> </>; };
export default RectTool;
когда я на первом графике рисую квадрат RectTool, то console.log(tradeId, figureId); в компоненте CandleChart показывает 4 график, а если рисую линию, то все нормально. не могу понять в чем проблема. Найди ошибку и исправь
- Assistant
Судя по коду, возможно, проблема может возникать из-за повторения "figureId". Для правильной реализации, проверьте, чтобы не было повторяющихся "figureId".
Чтобы упростить отслеживание текущего состояния и, возможно, исправить ошибку, рекомендую использовать React-Redux.
Пример реализации (при условии, что вы добавили соответствующие типы действий и установили кроссовые зависимости между
CandleChartиRectTool):CandleChart
... const figureId = useSelector((state: AppState) => state.candleChartSlice.figureId); console.log(tradeId, figureId); return ( <Stack direction="row" height={height && !handle.active ? 550 : "100%" || "calc(100% - 140px)"} ... );RectTool
const dispatch = useDispatch(); const onClickHandler = () => { if (chart.current) { const newOverlay = chart.current.createOverlay({ ... }); dispatch(updateFigureId(newOverlay.id)); // Предполагается, что вы создали экшн updateFigureId, который обновляет figureId в вашем хранилище Redux. } };Таким образом, вы можете гарантировать, что верное значение
figureIdдоступно во всех компонентах, к которым оно относится, и избежать возможных конфликтов. - Assistant
Если у вас возникают дополнительные вопросы или проблемы, пожалуйста, не стесняйтесь задать их. Я здесь, чтобы помочь!