reactjs 将从输入中选择的图像保存为对象状态,并将其呈现在页面上

atmip9wb  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(117)

只有当我把我的图像src改成AddProjects时它才起作用,而不是当它是AddProjects.Img时,这是我想要的。
我如何告诉React URL应该保存在AddProjects.Img中?下面是我的代码:

export default function AddProjects() {
  const [AddProjects, setAddProjects] = useState({
    name: "",
    Discription: "",
    git: "",
    Img: "",
  });
  // const [imgAdd,setImgAdd] = useState()
  const inputFile = useRef(null);
  function handleChange(e) {
    const { name, value } = e.target;
    setAddProjects((newProjects) => ({
      ...newProjects,
      [name]: value,
    }));
  }
  function imgChange(e) {
    console.log(e.target.files);
    setAddProjects(URL.createObjectURL(e.target.files[0]));
  }

  console.log(AddProjects);
  return (
    <div className="AddProjects">
      <form>
        <h2>Add New Project</h2>
        <input
          type="text"
          placeholder="Project Name..."
          value={AddProjects.name}
          name="name"
          onChange={handleChange}
        />
        <input
          type="text"
          placeholder="Project Discription..."
          value={AddProjects.Discription}
          name="Discription"
          onChange={handleChange}
        />
        <input
          type="text"
          placeholder="Git Repository/Code..."
          value={AddProjects.git}
          name="git"
          onChange={handleChange}
        />
        <input
          type="file"
          accept="image/jpg,image/jpeg"
          name="Img"
          onChange={imgChange}
          ref={inputFile}
        />
        <button type="button" onClick={() => inputFile.current.click()}>
          Add New Image
        </button>
        <button type="submit">Submit Project</button>
      </form>
      <img src={AddProjects.Img} alt="" />
    </div>
  );
}
ohtdti5x

ohtdti5x1#

imgChange函数就是这里的问题所在,因为你已经用图像URL替换了你的对象状态。

function imgChange(e) {
  setAddProjects({ ...AddProjects, Img: URL.createObjectURL(e.target.files[0]) });
}

相关问题