ReactJS表单不允许用户输入文本

owfi6suc  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(166)

我在ReactJS中创建了一个表单来接收用户的文本输入并将其存储在一个状态变量中。表单可以工作,但在重新加载网页后,表单不再允许我输入任何文本。这是表单的代码:

function UserInput({ generateResponse }) {
    const [prompt, setPrompt] = useState("");

    return (
        <>
            <form onSubmit={(e) => {
                e.preventDefault();
                generateResponse(prompt, setPrompt)
            }}>
                <input className="input-prompt" type="text" value={prompt} 
                onChange={(e) => setPrompt(e.target.value)} placeholder="type here..."/>
            </form>
        </>
    );
}

我尝试重写表单的输入标记代码,删除输入标记的'value'字段(尽管这在工作时没有产生任何问题)。我还尝试重新启动浏览器并在其他浏览器上尝试表单,但仍然不起作用。

qcbq4gxm

qcbq4gxm1#

try this one i am create a normal two field name and address and also submit button

import React, { useState } from "react";

const Form = ({ onSubmit }) => {
  const [formValues, setFormValues] = useState({
    name: "",
    address: ""
  });

  const handleChange = (e) => {
    const {
      target: { name, value }
    } = e;
    setFormValues({ ...formValues, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(JSON.stringify(formValues));
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <p>Name</p>
        <input 
          type="text" 
          name="name"
          value={formValues.name}
          onChange={handleChange}
        />
      </div>
      <div>
        <p>Address</p>
        <input 
          type="text" 
          name="address"
          value={formValues.address}
          onChange={handleChange}
        />
      </div>   
      <div>
        <button type="submit">Send</button>
      </div>
    </form>
  );
};

export default function App() {
  const showFormValues = (formValues) => alert(formValues);
  return (
    <div className="App">
      <h2>Contact Form</h2>
      <Form onSubmit={showFormValues} />
    </div>
  );
}

相关问题