input
使用技巧
onChange
事件选择同一个文件失效问题
使用value
置空
tsx
import { FormEvent, useRef, useState } from "react"
export default function Components() {
const handleChange = (e: FormEvent<HTMLInputElement>) => {
console.log(e.currentTarget.files)
e.currentTarget.value = ""
}
return (
<>
<input type="file" onChange={handleChange} />
</>
)
}
使用key
来强制刷新dom
tsx
import { FormEvent, useRef, useState } from "react"
export default function Components() {
const [time, setTime] = useState(performance.now())
/**
* 通过 key 强制渲染重置 input
* @param e
*/
const handleChange2 = (e: FormEvent<HTMLInputElement>) => {
console.log(e.currentTarget.files)
setTime(performance.now())
}
return (
<>
<input key={time} type="file" onChange={handleChange2} />
</>
)
}
使用form
重置方法
tsx
import { FormEvent, useRef, useState } from "react"
export default function Components() {
const formRef = useRef<HTMLFormElement>(null)
/**
* 通过 form reset 方法重置 input
* @param e
*/
const handleChange3 = (e: FormEvent<HTMLInputElement>) => {
console.log(e.currentTarget.files)
formRef.current?.reset()
}
return (
<>
<form ref={formRef}>
<input type="file" onChange={handleChange3} />
</form>
</>
)
}