首页 > 解决方案 > 反应页面内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(){}

这也行不通!

当我在空白页面中添加代码时,它工作正常,但在另一个页面中它给了我上面的错误。它应该等待页面加载(或类似的东西)

有人可以帮我解决这个问题吗?

谢谢你

标签: javascriptreactjsdom

解决方案


在这个工作 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;

推荐阅读