首页 > 解决方案 > reactjs中如何使用“document.getElementById('file').click()”

问题描述

我搜索了下面的 javascript 代码,我想在 Reactjs 中使用它:

    <input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('file').click();" />
    <input type="file" style="display:none;" id="file" name="file"/>

为了在 Reactjs 中使用它,我将其更改为:

    <input type="button" id="loadFileXml" value="loadXml" onClick={document.getElementById('file').click()} />
    <input type="file" style="display:none;" id="file" name="file"/>

但我收到错误消息Cannot read property 'click' of null。有人可以帮我弄清楚如何为此编写编写代码。

非常感谢。

标签: javascriptreactjs

解决方案


你不能以这种方式使用 react js。首先,您可以为显示属性使用状态。假设有一个类组件。我是手写的,可能是笔误。

import React, {Component} from 'react';

class Example extends Component {
 state = {
  isVisible : true ; 
} 

  changeVisible = () => {

    this.setState({

       isVisible : !this.state.isVisible // this working like a toggle button 
    })

   }

render (){
    return(
   <div>
        <button onClick = {this.changeVisible}> Change Visible </button>
        {
           //This section may be the item that you want to be visible or not
           isVisible ? <h1>I am Visible </h1> : null

        }
   </div>

)
}


} 
  export default Example;

推荐阅读