首页 > 解决方案 > 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?

也欢迎上述任何解决方案,谢谢。

标签: javascriptreactjs

解决方案


您只能在 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>

推荐阅读