如何在 React 中单击按钮打开 <input type="file"/>

kac*_*671 4 input button typescript reactjs

如何通过单击按钮打开文件输入?我的代码:

<Button variant="outlined">
      Choose Image
    </Button>
     <input
      type="file"
      id="input_file"
      accept=".jpg,.jpeg,.png"
      style={{ display: 'none' }}
     />
Run Code Online (Sandbox Code Playgroud)

小智 5

React >= 16.8 ,使用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
Run Code Online (Sandbox Code Playgroud)