React.js:未捕获的TypeError:无法将属性'innerHTML'设置为null [英] Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null

查看:344
本文介绍了React.js:未捕获的TypeError:无法将属性'innerHTML'设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 标记内的文本,但是我收到此错误Reactjs:未捕获TypeError:无法将属性 innerHTML设置为null。我遵循了文档。我错过了什么吗?

I need to access the text inside h1 tag in the check function, but I get this error Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null. I followed the documentation. Am I missing something?

推荐答案

参考是在第一个render()之后首先设置的。

The ref is first set after the first render()

一次检查演示演示

由于引用对象将组件的已安装实例作为当前实例,因此引用后立即引用该引用。

You're referring the ref immediately after it is declared, Since the ref object receives the mounted instance of the component as its current.

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

If you're trying to access the DOM at the same time it's trying to generate it. this.myRef will not return anything because the component has no real DOM representation in render.

这篇关于React.js:未捕获的TypeError:无法将属性'innerHTML'设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆