我是React的新手,javascript想要创建一个名称为“浏览”的链接,单击该链接应将文件作为输入,我在React的类组件中得到了很多答案,我该如何在函数组件中做到这一点。我尝试过:
center_length > 0
handleBrowse函数:
<div>
<br /><span>{i18n.gettext('- or - ')}</span>
<input id='logo-input' ref='logoInput' type='file' onChange={onFileSelected} type='hidden' />
<a href='' onClick={handleBrowse}>{ i18n.gettext('Browse')}</a>
<br />
</div>
onFileSelected函数:
const handleBrowse = function(e) {
e.preventDefault();
this.refs.logoInput.click();
};
当我这样做时,我得到如下错误:
const onFileSelected = function (e) {
const file = e.dataTransfer ? e.dataTransfer.files[0] : e.currentTarget.files[0];
handleFileSelection(file);
};
我了解功能组件不能具有ref,那么我该如何实现呢?
答案 0 :(得分:1)
如果您将组件重写为类,则也许该错误将消失
class MyComponent extends React.Component{
handleBrowse =(e) => {
e.preventDefault();
this.refs.logoInput.click();
};
onFileSelected = (e) => {
const file = e.dataTransfer ? e.dataTransfer.files[0] : e.currentTarget.files[0];
handleFileSelection(file);
};
render(){
return (
<div>
<br /><span>{i18n.gettext('- or - ')}</span>
<input id='logo-input' ref='logoInput' type='file' onChange={onFileSelected} type='hidden' />
<a href='' onClick={this.handleBrowse}>{ i18n.gettext('Browse')}</a>
<br />
</div>
)
}
}
作为无状态组件,它应该像这样工作:
const App = ()=>{
let myref = null;
const onFileSelected = (e)=>{
e.preventDefault();
console.log(e)
}
const handleBrowse = function (e) {
e.preventDefault();
myref.click();
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input id='logo-input' ref={(r) => {myref=r}} type='file' onChange={onFileSelected} />
<a onClick={handleBrowse}>{ i18n.gettext('Browse')}</a>
</div>
);
}