javascript - React Refs 在访问对 DOM 节点的引用时返回 null 或 undefined
问题描述
TypeError: Cannot read property 'value' of null
App._this.check_input_value
src/App.js:36
33 |
34 | check_input_value = () => {
35 |
> 36 | if (this.ref1.current.value != undefined && this.ref1.current.value != null) {
37 | console.log(this.ref1.current.value);
38 | }
39 | }
我还尝试只测试一个条件(!= null 和 undefined,分别)。相同的错误,除了我认为在测试 != null 时,它只是说属性未定义。
放入 if 语句来解决未定义/空值错误,删除它只会在下一条语句中产生相同的错误。
我从被引用的输入中的默认值开始,所以这不应该是一个问题:
// inside render()
<form action="">
<input
type="text"
ref={this.ref1}
value='10'
onChange={(e) => this.update_input_field(e)} />
<button
onClick={this.check_input_value()} >
Check input value
</button>
// Towards the top of the component, outside the constructor:
ref1 = React.createRef();
我还尝试this.ref1 = React.createRef()
在构造函数中进行设置。同样的错误。
constructor(props) {
super(props);
this.ref1 = React.createRef();
}
有谁知道为什么 this.ref1.current 返回 undefined 或 null?
也欢迎上述任何解决方案,谢谢。
解决方案
您只能在 componentDidMount 之后访问 ref。我在这里发现了一个错误:
<button
onClick={this.check_input_value()} >
Check input value
</button>
将this.check_input_value
在渲染而不是 onClick 时调用,之前componentDidMount
和 ref1 为空。改成这个
<button
onClick={this.check_input_value} >
Check input value
</button>
推荐阅读
- python-3.x - 动态导航栏元素 - 从 Flask 传递到 Jinja - 继承的布局模板
- python - 从 SciPy.ndimage 应用 Sobel 过滤器
- python - 如何通过键入函数名称而不使用方括号来调用 python 中的函数
- arrays - 如何通过向前一个条目添加一个元素来将值附加到 Bash 中的数组?
- javascript - 不带括号的 Javascript 警报
- javascript - 我的链接不工作它不会进入当前会话它会自动回家
- node.js - SequelizeJS:在表中获取最小 ID 和最大 ID 的最佳方法
- laravel - 安装版本:不适用
- python - 我正在尝试下一步格式化下拉菜单,但它似乎并没有让我
- arrays - pq: 函数 unnest(unknown) 不是唯一的