Reactjs:未捕获类型错误:无法设置 null 属性“innerHTML”

MrR*_*ot9 2 javascript dom reactjs react-component

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要访问函数中的text内部标签,但收到此错误 Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null。我按照文档进行操作。我错过了什么吗?h1check

Jay*_*vel 5

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

检查一次演示

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

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