属性addEventListener在react页内为null



我正在使用以下代码https://codepen.io/jotavejv/pen/bRdaVJ将其添加到我的反应页面。

当我单击浏览按钮时,它会重新加载页面,而不是打开文件选择器!

我试着添加:

async function componentDidMount() {
$("#triggerFile").addEventListener("click", evt => {
evt.preventDefault();
$("input[type=file]").click();
});  ...code continues                                                                                                                                  

异步不起作用。。也尝试过

window.onload=function(){}

这也不起作用!

当我在一个空白页面中添加代码时,它运行良好,但在另一个页面中,它会出现上述错误。Smh它应该等待页面加载(或类似的(

有人能帮我修一下吗?

谢谢

如何在React中完成此工作的repl的示例。

import React from 'react';
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.onBrowseClick = this.onBrowseClick.bind(this);
}
componentDidMount() {

}
onBrowseClick = () => {
this.inputRef.current.click();
};
render() {
return (
<div>
<input type="file" style={{display: 'none'}} ref={this.inputRef}></input>
<button onClick={this.onBrowseClick}>Browse</button>
</div>
);
}
}
export default App;

最新更新