【问题标题】:React file input onChange not changing the picture?反应文件输入onChange不改变图片?
【发布时间】:2021-09-27 11:58:57
【问题描述】:

我从用户那里获得了特定商店的缩略图。单击文件浏览按钮并打开图像时,这将为给定商店设置缩略图;但是,我还在缩略图的右上角添加了一个小 x 按钮,其实际用途是删除这张图片并添加一张新图片。我面临的主要问题是当我选择缩略图时,当我单击 x 按钮时,它会删除图像,但如果我选择相同的绘制图像,它不会将其添加为缩略图。所以我必须选择不同的图像来选择旧的。

import thumbnail from "../../../../Assets/thumbnail.png";
import deleteicon from "../../../../Assets/close.svg";
const thumbimage = dataType64toFile(thumbnail);
const [image, setImage] = useState(thumbimage);
const [filename, setFileName] = useState("Upload Image");
const [picture, setPicture] = useState(thumbnail);
const [close, setClose] = useState(false);




{close && (
          <img
            src={deleteicon}
            alt="Delete Thumbnail"
            className="thumbnail-close"
            onClick={() => {
              setImage(thumbimage);
              setPicture(thumbnail);
              setFileName("Upload Image");
              setClose(false);
            }}
          />
        )}


<Form.File
          type="file"
          label={filename}
          onChange={(e) => {
            setImage(e.target.files[0]);
            setFileName(e.target.files[0].name);
            setPicture(URL.createObjectURL(e.target.files[0]));
            setClose(true);
          }}
          custom
        />

【问题讨论】:

  • 你能把代码加到操场上吗?我最近要构建相同的 UI。为什么 setPicture(thumbnail) 和 setImage(thumbimage) 关闭?
  • @AshwinChandran setImage(thumbimage) 和 setPicture(thumbnail) 如果用户没有选择图像,则用于默认缩略图。

标签: javascript html reactjs webforms


【解决方案1】:

我最近创建了相同的图片库,但我的方法涉及到我的组件外部的自定义挂钩文件,即我只是将我所有的 useStates 和处理函数放在外面并从那里导入。

  • 首先进行调整,不要使用const [close, setClose] = useState(false);,而是使用image 进行检查。
  • 在单击删除图标时将文件和图像设置为空
  • 关于缩略图和其他不要设置它们! instead place the icon in the container and when an image is selected let it cover it!

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 2018-10-22
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2011-07-24
    • 2019-05-25
    相关资源
    最近更新 更多