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

Har*_*wal 5 javascript debugging input-type-file reactjs

I have an input type="file" and an input type="text". When I choose the file first and then put text in the input box and click the Add button, the picture doesn't show but when I put the text first and then choose the picture (file), it behaves normally.I think there's some problem in the inputKey That I have given. Here's a link from where I found this method http://robhoffmann.me/2016/03/12/Clearing-a-file-input-in-React/

What I am trying to do: I want to be able to choose an Image and type a product name which will then show on the screen. As soon as I click the Add button. I want both the inputs i.e. file type and text type to reset so that I can add the picture and Name of next product and so on..

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;
Run Code Online (Sandbox Code Playgroud)

当我单击“添加”按钮时,我希望输出显示productName和productPicture,但这仅在我首先输入文本然后选择图像/文件时发生,反之亦然。

rav*_*l91 1

通过做这个,

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

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

<input type="file" onChange={setImage} key={productPicture.inputKey} />
Run Code Online (Sandbox Code Playgroud)

功能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)
  }))
}
Run Code Online (Sandbox Code Playgroud)

演示

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