所以我遇到的问题是我试图每 5 秒打印一次 ref 的 textContent,这在第一次从 componentDidMount() 调用 typeWrite() 时有效,但是当它被递归调用时(使用setTimeout()) 时,我收到一条错误消息,指出 this.intro.current 未定义,即使它是在函数第一次运行时定义的。
我想保持结构相对相似(我不想改变太多),因为我遗漏了其他依赖于这个结构的东西。
export default class Home extends Component {
constructor(props) {
super(props);
this.intro = React.createRef();
}
componentDidMount() {
this.typeWrite();
}
typeWrite() {
console.log(this.intro.current.textContent);
setTimeout(this.typeWrite, 5000);
}
render() {
return (
<div className="intro" ref={this.intro}>Text</div>
)
}
}
最佳答案
您需要将函数绑定(bind)到组件。
constructor(props) {
super(props);
this.intro = React.createRef();
this.typeWrite = this.typeWrite.bind(this);
}
或者您需要使用箭头函数调用您的函数。
typeWrite() {
console.log(this.intro.current.textContent);
setTimeout(() => this.typeWrite(), 5000);
}
关于javascript - 引用未定义 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345735/