我的反应组件:
import React, { PropTypes, Component } from 'react'
class Content extends Component {
handleClick(e) {
console.log("Hellooww world")
}
render() {
return (
<div className="body-content">
<div className="add-media" onClick={this.handleClick.bind(this)}>
<i className="plus icon"></i>
<input type="file" id="file" style={{display: "none"}}/>
</div>
</div>
)
}
}
export default Content
在这里,当我单击带有图标的 div 时,我想打开一个<input>
文件显示了选择照片的选项。选择照片后,我想获取选择的照片的值。我怎样才能在反应中做到这一点?
首先,为您的input
.
const inputFile = useRef(null)
// or, for TypeScript
// const inputFile = useRef<HTMLInputElement | null>(null);
然后将其设置为您的input
并添加样式display: none
对于它,将其隐藏在屏幕上。
<input type='file' id='file' ref={inputFile} style={{display: 'none'}}/>
然后创建函数来处理打开的文件。该函数应该位于您正在使用的同一函数内useRef
hook.
const onButtonClick = () => {
// `current` points to the mounted file input element
inputFile.current.click();
};
然后将函数设置为button
元素:
<button onClick={onButtonClick}>Open file upload window</button>
HTML 输入文件的 API https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications#Using_hidden_file_input_elements_using_the_click()_method
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)