Когда изменяешь значение в input X,Y выдает такое предупреждение
Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
После того как уже изменил число и хочешь подвинуть div , X или Y увеличивает очень быстро свое значение и div уходит за окно предупреждение (2)
Warning: Received NaN for the value
attribute. If this is expected, cast the value to a string.
Код на codesandbox.io тут
import "./styles.css";
import React, { useRef, useState, useEffect } from "react";
const appStyle = {
fontFamily: "sansSerif",
textAlign: "center",
userSelect: "none"
};
const inputCStyle = {
width: "100px",
height: " 30px",
fontSize: "4vw",
position: "relative",
top: "0",
left: "0",
display: "flex",
cursor: "pointer"
};
const h1Style = {
display: "block",
margin: "0",
padding: "0",
marginLeft: "20px",
paddingRight: "10px"
};
const quickAndDirtyStyle = {
width: "200px",
height: "200px",
background: "#FF9900",
color: "#FFFFFF",
display: "flex",
justifyContent: "center",
alignItems: "center"
};
export default function App() {
const [pressed, setPressed] = useState(false);
const [position, setPosition] = useState({ x: 0, y: 0 });
const ref = useRef();
// Monitor changes to position state and update DOM
useEffect(() => {
if (ref.current) {
ref.current.style.marginLeft = `${position.x}px`;
ref.current.style.marginTop = `${position.y}px`;
}
}, [position]);
// Update the current position if mouse is down
const onMouseMove = (event) => {
if (pressed) {
setPosition({
x: position.x + event.movementX,
y: position.y + event.movementY
});
}
};
const handleChange = (e, type) => {
setPosition({
[type]: e.target.value
});
};
const inputCP = useRef();
const editItemCP = () => {
inputCP.current.select();
};
return (
<div className="App" style={appStyle}>
<div style={{ display: "flex" }}>
<h1 style={h1Style}>X</h1>
<input
style={inputCStyle}
className="inputC"
type="number"
value={position.x}
ref={inputCP}
onClick={editItemCP}
onChange={(e) => handleChange(e, "x")}
/>
<h1 style={h1Style}>Y</h1>
<input
style={inputCStyle}
className="inputC"
type="number"
value={position.y}
onChange={(e) => handleChange(e, "y")}
/>
</div>
<div
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%,-50%)"
}}
>
<div
ref={ref}
style={quickAndDirtyStyle}
onMouseMove={onMouseMove}
onMouseDown={() => setPressed(true)}
onMouseUp={() => setPressed(false)}
onMouseLeave={() => setPressed(false)}
>
<p>{pressed ? "Dragging..." : "Press to drag"}</p>
</div>
</div>
</div>
);
}