gpt4 book ai didi

javascript - 无法读取 null 的属性 'innerHTML'

转载 作者:行者123 更新时间:2023-11-28 19:26:25 25 4
gpt4 key购买 nike

尝试在我的关于类中创建一个简单的文本效果。我正在使用 React 来做这件事。它一直告诉我它无法读取属性 innerHTML。

我在想它看不到渲染中的元素,这就是为什么它认为它是空的。我该如何解决?

class About extends Component
{
constructor(props){
super(props)
this.loading = this.loading.bind(this)
}

loading() {
console.log('i got here')
let i = 0;
let txt = this.props.text;
let speed = 50;
function typeWriter() {
if ( i < txt.length){
document.getElementById("welcome").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter,speed);
}
}
typeWriter()
}


render()
{
return(
<div className="about">
<h1 id="welcome" onload = {this.loading()}></h1>
<p>some text</p>
</div>
);
}
}

我只是想将 Welcome 中的文本逐个字符地显示出来,有点像打字效果。

最佳答案

您应该使用 state 或 refs。然后在 componentDidMount 上运行你的函数,而不是使用 onload 函数。因此,对于 refs,它看起来像下面这样:

class About extends Component {
constructor(props) {
super(props);
this.loading = this.loading.bind(this);
this.elRef = React.createRef();
}

componentDidMount() {
this.loading();
}

loading() {
const el = this.elRef.current;
let i = 0;
let txt = 'Hello';
let speed = 50;
function typeWriter() {
if (i < txt.length) {
el.innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
typeWriter();
}

render() {
return (
<div className="about">
<h1 ref={this.elRef} />
<p>some text</p>
</div>
);
}
}

Dom 操作在 React 中有点棘手,因为它使用虚拟 DOM。因此,当您尝试操作它时,大多数时候该元素尚未呈现给实际的 DOM。因此,在操作 DOM 元素时,您需要使用 react refs React Refs或者您可以将您的值设置为状态。但在您的情况下,每次弹出一个字母时都会触发重新渲染,因此 refs 可能是您情况的最佳选择。

关于javascript - 无法读取 null 的属性 'innerHTML',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56080370/

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