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

问题描述 投票:0回答:3

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

<Button variant="outlined">
      Choose Image
    </Button>
     <input
      type="file"
      id="input_file"
      accept=".jpg,.jpeg,.png"
      style={{ display: 'none' }}
     />
reactjs typescript button input
3个回答
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

0
投票
  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' }} />

您在这里有答案如何将输入按钮链接到文件选择窗口


0
投票

也许这篇文章很旧,但我的帮助可能对某人有用。您可以使用:

<Button variant='outlined' component='label'>
    <input
      type='file'
      hidden
      onChange={e => handleChange(e)}
    />
    Choose Image
</Button>
© www.soinside.com 2019 - 2024. All rights reserved.