[英]How to trigger onChange on <input type='file' /> by another Button click in ReactJS?
<div style={{display: 'grid'}}>
<button id='plus' onClick={???}>+</button>
<input id='selectImage' type="file" onChange={fileSelectHandler} />
</div>
在這里,我想通過點擊按鈕來觸發輸入的onChange函數。 如何解決這個問題?
您可以隱藏原始文件輸入,並在單擊按鈕時通過javascript單擊。
upload() {
document.getElementById("selectImage").click()
}
<div style={{display: 'grid'}}>
<button id='plus' onClick={this.upload}>+</button>
<input id='selectImage' hidden type="file" onChange={fileSelectHandler} />
</div>
創建一個參考:
//inside the constructor:
fileRef = React.createRef()
// in your input element
<input id='selectImage' type="file" onChange={fileSelectHandler} ref={this.fileRef} />
現在,
<button id='plus' onClick={this.triggerClick}>+</button>
triggerClick() {
this.fileRef.current.click()
}
這對我很有效。 它將隱藏丑陋的文件輸入組件,並允許您在單擊按鈕時觸發其單擊功能。
import React from 'react'
import {
Button,
Input,
Label
} from 'reactstrap'
class UploadButton extends React.Component {
constructor(props) {
super(props)
this.fileInput = React.createRef() // ref to fileInput
}
// when called, triggers fileInput click function
triggerInputFile = () => {
if (this.fileInput.current != undefined && this.fileInput.current.click != undefined)
this.fileInput.current.click()
}
// handle file upload
handleFileUpload = () => {
// handle click
}
render() {
var color = 'primary'
return (
<div className='content'>
<Button
color={color}
onClick={() => this.triggerInputFile()}
>
Upload
</Button>
<input
ref={this.fileInput}
type='file'
onClick={() => this.handleFileUpload()}
style={styles.input}
/>
</div>
)
}
}
const styles = {
input: {
opacity: '0%', // dont want to see it
position: 'absolute' // does not mess with other elements
}
}
export default UploadButton
<div
class="col-lg-12 col-md-12 col-sm-12 "
onClick={() => {
this.upload.click();
}}
>
<h4 align="center">
<label class="theme-btn btn btn-style-three">
<span class="btn-title">
{" "}
Select From your device
</span>
</label>
</h4>
<input
name:'image'
style={{ visibility: "hidden" }}
type="file"
onClick={(e) => (e.target.value = null)}
ref={(ref) => (this.upload = ref)}
onChange={this.onChangeFile.bind(this)}
accept="image/*"`enter code here`
/>
</div>
上傳文件后將調用onChange
,單擊“選擇文件”輸入后將調用onClick
。 這就是你如何實現這一目標:
class SomeComponent extends React.Component {
constructor(props) {
super(props);
}
fileSelectHandler=()=> {
console.log("changed")
}
clickhandler = () => {
console.log("clicked")
}
render() {
return (
<div style={{ display: 'grid' }}>
<button id='plus' />
<input id='selectImage' type="file" onClick={this.clickhandler} onChange={this.fileSelectHandler} />
</div>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.