一个容器组件:
class FooContainer extends React.Component {
...
}
其中渲染一个隐藏的 <input>
render() {
return (
...
<input hidden type="file"/>
...
)
}
在构造函数中通过React.createRef()
创建Refs
并通过ref
属性联系到React
组件,假设需要关联组件的变量名为inputElement
。
constructor(props) {
super.(props)
this.inputElement = React.createRef()
}
为 <input>
添加 ref
属性
render() {
return (
...
<input hidden type="file" ref={this.inputElement}/>
...
)
}
渲染一个按钮,并绑定它的onClick
事件,在回调函数中即可通知 inputElement
点击:
...
handleFileInputClick = (event) => {
event.preventDefault()
this.inputElement.current.click()
}
render() {
return (
...
<input hidden type="file" ref={this.inputElement}/>
<a onClick={this.handleFileInputClick}>上传文件</a>
...
)
}
...