如何通过单击按钮打开输入的文件?我的代码:
<Button variant="outlined">
Choose Image
</Button>
<input
type="file"
id="input_file"
accept=".jpg,.jpeg,.png"
style={{ display: 'none' }}
/>
useRef
钩子import React, { useRef } from 'react'
const MyComponent = () => {
const ref = useRef()
const handleClick = (e) => {
ref.current.click()
}
return (
<>
<button onClick={handleClick}>Upload Image</button>
<input ref={ref} type="file" />
</>
)
}
export default MyComponent
const Open = () => {
document.getElementById('get_file').onclick = function() {
document.getElementById('input_file').click();}}
<button id="get_file" variant="outlined" onClick={() => Open() } > Choose Image </button>
<input type="file" id="input_file" accept=".jpg,.jpeg,.png" style={{ display: 'none' }} />
您在这里有答案如何将输入按钮链接到文件选择窗口
也许这篇文章很旧,但我的帮助可能对某人有用。您可以使用:
<Button variant='outlined' component='label'>
<input
type='file'
hidden
onChange={e => handleChange(e)}
/>
Choose Image
</Button>