javascript - 反应页面内null的属性addEventListener
问题描述
我正在使用此代码https://codepen.io/jotavejv/pen/bRdaVJ将其添加到我的反应页面。
当我单击“浏览”按钮时,它会重新加载页面而不是打开文件选择器!
我试图添加:
async function componentDidMount() {
$("#triggerFile").addEventListener("click", evt => {
evt.preventDefault();
$("input[type=file]").click();
}); ...code continues
异步不起作用..也尝试过
window.onload=function(){}
这也行不通!
当我在空白页面中添加代码时,它工作正常,但在另一个页面中它给了我上面的错误。它应该等待页面加载(或类似的东西)
有人可以帮我解决这个问题吗?
谢谢你
解决方案
在这个工作 repl中如何在 React 中完成它的示例。
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;
推荐阅读
- python - 清理时出现python多进程socket.error
- javascript - 0 在 ES6 中被认为是真的吗?
- file - 从外部访问共享首选项/将值存储到新文件中并从外部访问它
- javascript - 有没有办法用代码“清除网站数据”浏览器?
- javascript - 在Javascript中,有没有一种多态设置器的方法
- visual-studio - Visual Studio 从另一个文件打开类的文件
- sql - 我有两列,我想将两者结合起来,而不是通过 concat 仅结合另一行下方的一行
- python - 使用 sqlalchemy 查询远程数据库后 SSHTunnelForwarder 未结束
- node.js - 如何从客户端向服务器发出异步请求?
- vue.js - 将集合复制出 vuex 状态以防止突变是标准的吗?