【问题标题】:Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of nullReactjs:未捕获的 TypeError:无法将属性“innerHTML”设置为 null
【发布时间】:2023-04-09 07:05:01
【问题描述】:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class Game extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.check = this.check.bind(this);
  }


 drawBackground() {
    console.log("worked");
}

  check () {
    this.myRef.current.innerHTML  = "Testing";
    {this.drawBackground()}      
  }

  render() {
    return (
        <div>
          <h1 ref={this.myRef} id="foo">bar</h1>
          {this.check()}
</div>
    );
  }
}

我需要在check 函数中访问h1 标记内的text,但我收到此错误 Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null。我遵循了文档。我错过了什么吗?

【问题讨论】:

    标签: javascript reactjs dom react-component


    【解决方案1】:

    在第一次render()之后首先设置ref

    查看演示一次demo

    您是在声明 ref 后立即引用它,因为 ref 对象接收已安装的组件实例作为其当前实例。

    如果您在尝试访问 DOM 的同时它会尝试生成它。 this.myRef 不会返回任何内容,因为该组件在渲染中没有真正的 DOM 表示。

    【讨论】:

      【解决方案2】:

      您需要将值分配给 ref。 您将 ref 作为函数传递。

      class App extends React.Component {
        constructor(props) {
          super(props);
          this.check = this.check.bind(this);
        }
      
        state = {
          dom: null
        };
      
        drawBackground() {
          console.log("worked");
        }
      
        componentDidMount() {
          this.check();
        }
      
        check() {
          const innerHTML = ReactDOM.findDOMNode(this.myRef).innerHTML;
          setTimeout(
            () => (ReactDOM.findDOMNode(this.myRef).innerHTML = "TEST"),
            1000
          );
          console.log(innerHTML);
          this.setState({
            dom: innerHTML
          });
          {
            this.drawBackground();
          }
        }
      
        render() {
          return (
            <div>
              <h1 ref={ref => (this.myRef = ref)} id="foo">
                bar
              </h1>{" "}
              //You need to assign the value of the ref to the instance variable
            </div>
          );
        }
      }
      

      【讨论】:

      • 让我创建一个代码框示例来解释这一点
      • 你为什么在渲染中执行this.check()
      • 很高兴为您提供帮助 :)
      猜你喜欢
      • 2020-12-29
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 2020-12-19
      • 1970-01-01
      • 2014-08-20
      相关资源
      最近更新 更多