首页 > 解决方案 > 表单输入不允许在 React 表单上更改值

问题描述

我试图允许用户在表单输入中输入 ID。当他们点击提交时,它会将该表单输入值发送到 API url 以获取具有该 ID 的项目。目前,我在表单输入中看到默认值并且可以点击提交,但我无法更改输入中的值。我如何允许这样做,以便用户可以修改 ID 然后用它发送请求?然后我会用钩子处理响应

const Items: React.FC = () => {
  interface Item {
    id?: number;
    name?: string;
  }

  let default = { value: "123456" };
  const [item, setItem] = useState<Item>({});
  const handleChange = (e: React.ChangeEvent<any>) => {
   console.log(e.target.value)
  };

  const handleSubmit = (e: React.ChangeEvent<any>) => {
    e.preventDefault();
    console.log(e.target.value);
    axios
      .get(
        `myUrl/${item:id}` <- here I want to insert the ID from the form input into the request url
      )
      .then((response) => setItem(response.data))
      .catch((error) => console.log(error));
  };


  return (
    <div className="toolbar-content">
      <div className="row">
        <form onSubmit = { handleSubmit }>
          <div className="label"> MAC Address:</div>
          <Input  value={default.value} onChange={handleChange}/> <- here is where there should be a default value. Then if the user changes it and hits submit, send that value to the handleSubmit function
          <Button className="btn" type="submit">
            SUBMIT
          </Button>
        </form>
      </div>
    </div>
  );
};

export default Gateways;

谢谢!

标签: reactjstypescriptformsreact-hooks

解决方案


您的 handleChange 函数应该处理这个问题。创建一个 textValue 状态并在 handleChange 函数中,将文本值设置为输入的目标值:

const Items: React.FC = () => {
  interface Item {
    id?: number;
    name?: string;
  }

  let default = { value: "123456" };
  const [item, setItem] = useState<Item>({});
  const [textValue, setTextValue] = useState(default.value);
  const handleChange = (e: React.ChangeEvent<any>) => {
   setTextValue(e.target.value)
  };

  const handleSubmit = (e: React.ChangeEvent<any>) => {
    e.preventDefault();
    console.log(e.target.value);
    axios
      .get(
        `myUrl/${item:id}` <- here I want to insert the ID from the form input into the request url
      )
      .then((response) => setItem(response.data))
      .catch((error) => console.log(error));
  };


  return (
    <div className="toolbar-content">
      <div className="row">
        <form onSubmit = { handleSubmit }>
          <div className="label"> MAC Address:</div>
          <Input  value={textValue} onChange={handleChange}/> <- here is where there should be a default value. Then if the user changes it and hits submit, send that value to the handleSubmit function
          <Button className="btn" type="submit">
            SUBMIT
          </Button>
        </form>
      </div>
    </div>
  );
};

export default Gateways;

推荐阅读