javascript - 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
。有人可以帮我弄清楚如何为此编写编写代码。
非常感谢。
解决方案
你不能以这种方式使用 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;
推荐阅读
- python - 如何在 Python 中定义每个维度中具有不同单位的二维数量数组
- python - Tkinter 输入框总是空的?
- int - Pinescript:强制变量采用整数值
- c++ - Premake5 编译额外的可执行文件
- node.js - 发布到 symfony 端点的 Node.js 表单数据为 NULL
- google-cloud-platform - 尽管检查了防火墙规则,但与谷歌云上的虚拟机实例的 HTTP 连接失败
- javascript - 为什么我在使用 Sequelize 填充字段时遇到错误?
- haskell - Haskell 中的“f (a -> b)”类型签名是什么意思?
- opencl - OpenCl:如何使用 INT4/8?
- ruby-on-rails - 如何使 sprockets(或 rack,或 nginx?)激励浏览器缓存字体并正确返回 304?