[英]I have buttons and a textbook in my React App, How do I make the click of the button trigger text input?
[英]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>
);
}
您可以在不使用任何 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>
你可以在这里确认。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.