reAct element reszize не работает < /p>
Я пытаюсь реализовать изменяемый контейнер в чате в React, но функциональность изменения размера не работает должным образом, уже потраченная полдня. Я подозреваю, что проблема заключается в моей функции Mousedownhandler , в частности, с логикой обнаружения положения мыши.
Resize Issue
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body { min-height: 100dvh; }
#root { width: 100%; min-height: inherit; }
.appContainer {
width: 100vw;
height: 100dvh;
padding: 10px;
display: flex;
gap: 10px;
background: #000;
}
.aside {
background: #aaa;
height: 100%;
min-width: 320px;
width: 500px;
}
.chatContainer {
width: 100%;
height: 100%;
min-width: 400px;
background: #aaa;
}
< /code>
import React, { useState, useRef, useLayoutEffect } from "react";
import { createRoot } from "react-dom/client";
const root = createRoot(document.querySelector("#root"));
function Chat() {
const MIN_WIDTH = 400;
const MAX_WIDTH = 1400;
const [width, setWidth] = useState(null);
const container = useRef(null);
const isMoving = useRef(false);
const startX = useRef(null);
const startWidth = useRef(null);
useLayoutEffect(() => {
const w = container.current.offsetWidth;
setWidth(w);
function mouseDownHandler(e) {
e.preventDefault();
if (e.target !== container.current) return;
const elem = container.current;
const rect = elem.getBoundingClientRect();
const x = e.clientX;
startX.current = x;
startWidth.current = elem.offsetWidth;
if (rect.x - x + 15 >= 0) isMoving.current = true;
}
function mouseMoveHandler(e) {
e.preventDefault();
if (!isMoving.current) return;
const delta = e.clientX - startX.current;
let newWidth = startWidth.current - delta;
if (newWidth < MIN_WIDTH) newWidth = MIN_WIDTH;
if (newWidth > MAX_WIDTH) newWidth = MAX_WIDTH;
setWidth(newWidth);
}
function mouseUpHandler(e) {
e.preventDefault();
if (isMoving.current) isMoving.current = false;
startX.current = null;
startWidth.current = null;
}
document.addEventListener("mousedown", mouseDownHandler);
document.addEventListener("mousemove", mouseMoveHandler);
document.addEventListener("mouseup", mouseUpHandler);
return () => {
document.removeEventListener("mousedown", mouseDownHandler);
document.removeEventListener("mousemove", mouseMoveHandler);
document.removeEventListener("mouseup", mouseUpHandler);
};
}, []);
return (
);
}
root.render(
);
Подробнее здесь: https://stackoverflow.com/questions/797 ... t-in-react
Как исправить этот режисский компонент в React? ⇐ Javascript
Форум по Javascript
-
Anonymous
1756387983
Anonymous
reAct element reszize не работает < /p>
Я пытаюсь реализовать изменяемый контейнер в чате в React, но функциональность изменения размера не работает должным образом, уже потраченная полдня. Я подозреваю, что проблема заключается в моей функции Mousedownhandler , в частности, с логикой обнаружения положения мыши.
Resize Issue
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body { min-height: 100dvh; }
#root { width: 100%; min-height: inherit; }
.appContainer {
width: 100vw;
height: 100dvh;
padding: 10px;
display: flex;
gap: 10px;
background: #000;
}
.aside {
background: #aaa;
height: 100%;
min-width: 320px;
width: 500px;
}
.chatContainer {
width: 100%;
height: 100%;
min-width: 400px;
background: #aaa;
}
< /code>
import React, { useState, useRef, useLayoutEffect } from "react";
import { createRoot } from "react-dom/client";
const root = createRoot(document.querySelector("#root"));
function Chat() {
const MIN_WIDTH = 400;
const MAX_WIDTH = 1400;
const [width, setWidth] = useState(null);
const container = useRef(null);
const isMoving = useRef(false);
const startX = useRef(null);
const startWidth = useRef(null);
useLayoutEffect(() => {
const w = container.current.offsetWidth;
setWidth(w);
function mouseDownHandler(e) {
e.preventDefault();
if (e.target !== container.current) return;
const elem = container.current;
const rect = elem.getBoundingClientRect();
const x = e.clientX;
startX.current = x;
startWidth.current = elem.offsetWidth;
if (rect.x - x + 15 >= 0) isMoving.current = true;
}
function mouseMoveHandler(e) {
e.preventDefault();
if (!isMoving.current) return;
const delta = e.clientX - startX.current;
let newWidth = startWidth.current - delta;
if (newWidth < MIN_WIDTH) newWidth = MIN_WIDTH;
if (newWidth > MAX_WIDTH) newWidth = MAX_WIDTH;
setWidth(newWidth);
}
function mouseUpHandler(e) {
e.preventDefault();
if (isMoving.current) isMoving.current = false;
startX.current = null;
startWidth.current = null;
}
document.addEventListener("mousedown", mouseDownHandler);
document.addEventListener("mousemove", mouseMoveHandler);
document.addEventListener("mouseup", mouseUpHandler);
return () => {
document.removeEventListener("mousedown", mouseDownHandler);
document.removeEventListener("mousemove", mouseMoveHandler);
document.removeEventListener("mouseup", mouseUpHandler);
};
}, []);
return (
);
}
root.render(
);
Подробнее здесь: [url]https://stackoverflow.com/questions/79749084/how-to-fix-this-resizable-component-in-react[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия