簡體   English   中英

如何讓按鈕在 React 中觸發文件輸入 onChange?

[英]How do I make a button trigger a file input onChange in React?

我有一個文件類型的輸入。 出於某種原因,它不允許我將 value 屬性更改為它,而且看起來很難看。 我用一個按鈕交換了它,但現在我需要該按鈕以某種方式在單擊時觸發輸入文件 我如何在 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>

您可以簡單地使用 label:

 .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">

你不應該把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>
  );
}

編輯angerous-banzai-6vwg3

您可以在不使用任何 JS 的情況下使用 html label元素:


const Component = () => {
  // You should also use a ref instead of document.getElementById
  const inputRef = useRef() 

  return (
    <label>
      <div> {/*Style this however you want*/}
        Upload Photo
      </div>
      <input type="file" style={{display: "none"}} ref={inputRef} />
    </label>
   )
}

我認為你可以這樣做。

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM