输入类型="file" 与其他输入类型一起使用时表现出奇怪的行为

Input type="file" showing weird behavior when used along with another input type

我有一个输入 type="file" 和一个 input type="text"。当我先选择文件然后在输入框中输入文字并点击添加按钮时,图片不显示但是当我先输入文字然后选择图片(文件)时,它的行为normally.I认为我提供的 inputKey 有问题。这是我从中找到此方法的 link http://robhoffmann.me/2016/03/12/Clearing-a-file-input-in-React/

我想做什么:我希望能够选择一个图像并键入一个产品名称,然后该名称将显示在屏幕上。只要我点击添加按钮。我想要重置输入,即文件类型和文本类型,以便我可以添加下一个产品的图片和名称等等。

function Admin(props){

    const [productName, setproductName] = React.useState("");

    let [productPicture, setproductPicture] = React.useState({file:null,inputKey:Date.now()});


    return (
        <div>
            <Link to="/">Go back</Link><br/><br/>
            <input type="file" onChange={(e)=>(productPicture=URL.createObjectURL(e.target.files[0]))} key={productPicture.inputKey}></input><br/>
            <input type="text" required placeholder="Product Name" onChange={(e)=>setproductName(e.target.value)} value={productName}></input><br/><br/>

<button type="Submit" onClick={(e)=>{props.AddInfo({productName,productPicture});setproductName("");setproductPicture({file:null,inputKey:Date.now()})}}>Add</button>
            <br/><br/>

            <div>
             {props.products.map((x)=>(<div>{x.name} {typeof x.picture === 'string' ? <img src={x.picture} alt="Product Picture" style={{width:"250px"}}></img>:""} </div>))}   
            </div>
        </div>
    )
}

export default Admin;

我希望在单击“添加”按钮时输出显示 productName 和 productPicture,但这只会在我先输入文本然后选择 image/file 时发生,反之亦然。

通过这样做,

<input type="file" onChange={(e)=>(productPicture=URL.createObjectURL(e.target.files[0]))} key={productPicture.inputKey}></input><br/>

您是在直接尝试改变状态,productPicture=URL.createObjectURL(e.target.files[0]) 这是错误的。在这里你没有设置状态。要设置实际状态,您需要使用 setproductPicture setter 函数。

<input type="file" onChange={setImage} key={productPicture.inputKey} />

setImage函数应该是,

const setImage = (e) => {
  console.log(e.target.files[0].name);
  let file = e.target.files[0];  //Capture the file in variable otherwise event gets nullified and you won't get file.
  setproductPicture(prevState=>({
     ...prevState,
     file: URL.createObjectURL(file)
  }))
}

Demo

注意:input是空标签,不要像<input></input>那样关闭。你可以这样做,<input />