如何在React中通过按钮触发文件输入的onChange事件?

4

我有一个文件输入框,类型为 file。由于某些原因,它不允许我更改值属性,并且看起来很难看。我用按钮替换了它,但现在我需要的是在单击按钮时以某种方式触发文件输入框。在React中如何实现呢?

编辑:

它应该在 onClick 事件上触发输入框,而不是标题所说的 onChange。除非在这种情况下它是一样的。

const fireInput = () => {
  let input = document.getElementById('inputFile');
}

<div>
  <input 
    id="inputFile"
    type='file'
    className='mt-2 mb-3 text-primary'
    onChange={uploadProfilePic}
  />
  <button
    type='button'
    className='btn btn-primary py-2 px-5 mb-3'
    onClick={fireInput}
  >
  Upload Picture
  </button>
</div>
4个回答

4

不应该使用display:none,否则元素将不会在DOM中存在。您需要使用opacity:0或visibility css。

可以像这样编写执行上述操作的代码:

import "./styles.css";
import { useRef } from "react";

export default function App() {
  const fileUpload = useRef(null);
  const uploadProfilePic = (e) => {
    console.log(e);
  };

  const handleUpload = () => {
    console.log(fileUpload.current.click(), "fileUpload");
  };
  return (
    <div className="App">
      <input
        type="file"
        ref={fileUpload}
        onChange={uploadProfilePic}
        style={{ opacity: "0" }}
      />
      <button onClick={() => handleUpload()}>Upload Picture</button>
    </div>
  );
}

Edit angry-banzai-6vwg3


它在沙盒中无法运行。返回一个错误。 - cris
请再检查一遍,有一个错误,我没有保存更改。 - Goutham J.M

2
您可以简单地使用一个标签:

.d-none {
  display: none;
}

.button {
  background-color: #123456;
  color: white;
  padding: 15px 32px;
  text-align: center;
}
<label for="inputFile" class="button">Upload</label>
<input type="file" id="inputFile" name="inputFile" class="d-none">


1
你可以使用HTML的

0

我认为你可以这样做。

<div>
  <input type="file" onChange={uploadProfilePic} ref={(ref) => this.upload = ref} style={{ display: 'none' }}/>
  <button                
    type='button'
    className='btn btn-primary py-2 px-5 mb-3'
    onClick={(e) => this.upload.click()}
  >
    Upload Picture
  </button>
</div>
                                
                                

您可以在这里确认。

https://codesandbox.io/s/youthful-cdn-lpntx


这是什么.upload? - cris
这是输入的引用。 - BTSM
您可以在 CodeSandbox 上进行确认。我已经添加了 URL。 - BTSM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接