gpt4 book ai didi

javascript - Reactjs:未捕获类型错误:无法设置 null 的属性 'innerHTML'

转载 作者:行者123 更新时间:2023-11-28 17:13:36 27 4
gpt4 key购买 nike

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属性“innerHTML”为空。我按照文档进行操作。我错过了什么吗?

最佳答案

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

检查一次演示 demo

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

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

关于javascript - Reactjs:未捕获类型错误:无法设置 null 的属性 'innerHTML',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53955693/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com