{ consol-6ren">
gpt4 book ai didi

reactjs - 无法到达 react 组件的引用

转载 作者:行者123 更新时间:2023-12-03 14:21:25 25 4
gpt4 key购买 nike

我使用 ref="canvas"属性创建了 canvas 元素。当我尝试将它们放入 componentDidMount 中时:

componentDidMount = () => {
console.log(this.refs);
}

有空对象。

但是,那我就这么做了

componentDidMount = () => {
console.log(this);
}

我看到 React 元素带有包含我的 Canvas 的非空“refs”对象!

怎么会发生这种事?

最佳答案

我认为问题在于您将 componentDidMount 的值设置为一个函数,该函数将进行评估以设置 componentDidMount 的结果。此时,this.refs 尚未填充,因为组件正在触发该函数预渲染。但是,通过仅记录 this,控制台最终将获取更新的组件,以便您可以在其中看到 refs。以下是您应该如何构建该组件:

componentDidMount() {
console.log(this.refs)
}

这有道理吗?你所做的相当于这个......

class Foo {
bar = () => {
console.log('I get called when foo loads to determine the value of bar')
}
}

而不是这个

class Foo {
bar() {
console.log('I get called with bar()')
}
}

我无法实际测试我的代码,因为此语法无效,所以我不确定它如何为您工作......

关于reactjs - 无法到达 react 组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37304057/

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