未捕获的DOMException:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串

问题描述

我已经上传并成功获取了产品列表,但“更新产品”为我显示一个错误我不知道如何在Reactjs中更新Firebase上的图像和数据。

这是我在ProductForm.js中的代码

import React,{ useState,useEffect } from 'react';
import Gongcha from '../asses/gongcha.jpg'

const ProductForm = (props) => {
  const initialFieldValues = {
    image: '',name: '',category: '',price: ''
  };

  var [values,setValues] = useState(initialFieldValues);
  var [imageFile,setimageAsFile] = useState();

  useEffect(() => {
    if (props.currentId == '') setValues({ ...initialFieldValues });
    else
      setValues({
        ...props.productObjects[props.currentId],});
  },[props.currentId,props.productObjects]);

  const handleInputChange = (e) => {
    var { name,value } = e.target;
    setValues({
      ...values,[name]: value,});
  };

  const handleFormSubmit = (e) => {
    e.preventDefault();
    props.addOrEdit(values,imageFile);
  };
  const handleImageAsFile = (e) => { 
    console.log("file image",e);
    const image = e.target.files[0]
    setimageAsFile(imageFile => (image))
}

  return (
    <form autoComplete="off" onSubmit={handleFormSubmit}>
      <div className="form-group input-group">
        <div className="input-group-prepend">
          <div className="input-group-text">
            <i className="fas fa-image"></i>
          </div>
        </div>
        <input
          className="form-control"
          type="file"
          name="image"
          placeholder="Image"
          value={values.image}
          onChange={handleImageAsFile}
        />
      </div>
      <div className="form-row">
        <div className="form-group input-group col-md-6">
          <div className="input-group-prepend">
            <div className="input-group-text">
              <i className="fas fa-mug-hot"></i>
            </div>
          </div>

          <input
            className="form-control"
            name="name"
            placeholder="Name"
            value={values.name}
            onChange={handleInputChange}
          />
        </div>
        <div className="form-group input-group col-md-6">
          <div className="input-group-prepend">
            <div className="input-group-text">
              <i className="fas fa-list-alt"></i>
            </div>
          </div>
          <input
            className="form-control"
            name="category"
            placeholder="Category"
            value={values.category}
            onChange={handleInputChange}
          />
        </div>
      </div>
      <div className="form-group input-group">
        <div className="input-group-prepend">
          <div className="input-group-text">
            <i className="fas fa-money-check-alt"></i>
          </div>
        </div>
        <input
          className="form-control"
          name="price"
          placeholder="Price"
          value={values.price}
          onChange={handleInputChange}
        />
      </div>
      <div className="form-group">
        <input
          type="submit"
          value={props.currentId == '' ? 'Save' : 'Update'}
          className="btn btn-primary btn-block"
        />
      </div>
    </form>
  );
};

export default ProductForm;

这是表,我在其中显示了所有产品列表以及操作(编辑和删除

import React,useEffect } from 'react';
import { Card,Button,Imgage } from 'react-bootstrap'
import ProductForm from './ProductForm';
import { DB,Storage } from '../firebase';    

const Products = () => {
  var [currentId,setCurrentId] = useState('');
  var [productObjects,setProductObjects] = useState({});
  const [ImageAsUrl,setimageAsUrl] = useState()


  useEffect(() => {
    DB.ref().child('products').on('value',(snapshot) => {
      if (snapshot.val() != null) {
        setProductObjects({
          ...snapshot.val(),});
      }
    });
  },[]);

  const addOrEdit = (obj,image_url) => {

    let upload = Storage.ref().child(`product-img/${image_url.name}`).put(image_url)
    upload.on('state_changed',(snapShot) => {

        console.log(snapShot)
      },(err) => {

        console.log(err)
      },() => {

        Storage.ref('product-img').child(image_url.name).getDownloadURL()
          .then(fireBaseUrl => {

            DB.ref().child('products').push({ name: obj.name,image: fireBaseUrl,category: obj.category,price: obj.price },(err) => {

              if (err) console.log(err);
              else setCurrentId('');
            })

          })
      })

    console.log("log imgage link",ImageAsUrl);
  };

  const onDelete = (id) => {
    if (window.confirm('Are you sure to delete this record?')) {
      DB.ref().child(`products/${id}`).remove((err) => {
        if (err) console.log(err);
        else setCurrentId('');
      });
    }
  };

  return (
    <>
      <div className="jumbotron jumbotron-fluid">
        <div className="container">
          <h1 className="display-4 text-center">Products Manager</h1>
        </div>
      </div>
      <div className="row">
        <div className="col-md-5">
          <ProductForm {...{ currentId,productObjects,addOrEdit }} />
        </div>
        <div className="col-md-7">
          <table className="table table-borderless table-stripped">
            <thead className="thead-light">
              <tr>
                <th>Image</th>
                <th>Name</th>
                <th>Category</th>
                <th>Price</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {Object.keys(productObjects).map((key) => (
                <tr key={key}>
                  <td>{productObjects[key].image}</td>
                  <td>{productObjects[key].name}</td>
                  <td>{productObjects[key].category}</td>
                  <td>{productObjects[key].price}</td>
                  <td className="bg-light">
                    <a
                      type="button"
                      className="btn text-primary"
                      onClick={() => {
                        setCurrentId(key);
                      }}
                    >
                      <i className="fas fa-pencil-alt"></i>
                    </a>
                    <a
                      type="button"
                      className="btn text-danger"
                      onClick={() => {
                        onDelete(key);
                      }}
                    >
                      <i className="far fa-trash-alt"></i>
                    </a>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

export default Products;

当我单击Update图标时,这是我的错误显示

enter image description here

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename,which may only be programmatically set to the empty string.

enter image description here

有人可以帮助我解决这个问题吗?我真的不知道该如何解决。请?您的帮助是我的荣幸

解决方法

如错误所解释,您不能在输入/文件元素上设置value属性。简短示例:

<input type="file" value="this throws an error" />

这意味着,如果用户已经上传了文件,则无法“预填充”输入字段。您可以显示文件(如果是图片)并在文件旁边添加删除选项(例如按钮)。