<div style={{display: 'grid'}}>
<button id='plus' onClick={???}>+</button>
<input id='selectImage' type="file" onChange={fileSelectHandler} />
</div>
在这里,我想通过单击按钮来触发输入的onChange函数。如何解决这个问题?
答案 0 :(得分:2)
创建参考:
//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()
}
答案 1 :(得分:1)
您可以隐藏原始文件输入,并通过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>
答案 2 :(得分:1)
这对我来说很好。它将隐藏难看的文件输入组件,并允许您在单击按钮时触发其单击功能。
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
答案 3 :(得分:-1)
--
,单击“选择文件”输入后,将调用onChange
。就是这样实现的:
onClick