1

Когда изменяешь значение в 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>
  );
}

1 ответ 1

2

Первая проблема заключается в [type]: e.target.value, в value хранится строка, а не число. Это мы решаем с помощью замены e.target.value на Number(e.target.value) или же как подсказал в комментариях @Избыток сусликов на e.target.valueAsNumber.
Вторая проблема это то, что после:

setPosition({
  [type]: e.target.value
});

В стейте оказывается объект лишь из одного свойства (допустим {x: 100} или {y: 100}), чтобы этого избежать, вам нужно развернуть старый стейт в новый объект с [type]: e.target.value, а точнее [type]: Number(e.target.value).

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((prev) => {
      return { ...prev, [type]: e.target.valueAsNumber }; // или же вместо e.target.valueAsNumber делаем Number(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>
  );
}
3
  • 3
    Если тип инпута number, то можно просто взять число через свойство valueAsNumber ;)
    – Randall
    4 сен 2022 в 18:00
  • Оу.. Ведь когда-то я его встречал, но оно забылось как страшный сон) Спасибо за освежение памяти) 4 сен 2022 в 18:01
  • Да не за что ^_^
    – Randall
    4 сен 2022 в 18:02

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.