问题描述
我有一个 ref
的元素已经定义并最终被渲染到页面中:
I have an element with a ref
that is defined and ends up getting rendered into the page :
<div ref="russian" ...>
...
</div>
我想访问DOM元素属性,如 offset ...
或其他什么。但是,我一直得到 undefined
,我不知道原因。经过一番搜索后,很明显 refs
只适用于一个文件,但除了这一页之外,我没有在任何地方使用它。我这样说是为了记录它:
I want to access the DOM element properties like offset...
or something. However, I keep getting undefined
and I haven't the faintest idea why. After some searching it's clear that refs
are only applicable to one file but I'm not using this anywhere besides this one page. I'm saying this to log it:
console.log('REFS',this.refs.russian);
造成这种情况的原因是什么?
What could be causing this?
推荐答案
正确使用 refs
的地方是特定的React生命周期方法,例如,
The correct place to work with refs
is inside specific React lifecycle methods e.g. ComponentDidMount, ComponentDidUpdate
你不能引用 render()方法的code> refs 。
You cannot reference refs
from the render()
method. Read more about the cautions of working with refs
here.
如果您移动 console.log('REFS',this.refs。俄语);
调用 ComponentDidMount
或 ComponentDidUpdate
生命周期方法(假设你在React上> = 14)你不应该得到 undefined 。
If you move your console.log('REFS', this.refs.russian);
call to ComponentDidMount
or ComponentDidUpdate
lifecycle methods (assuming you are on React >= 14) you should not get undefined as a result.
UPDATE:也refs不能用于无状态组件根据上面的警告链接
UPDATE: also refs will not work on stateless components per the caution link above
这篇关于this.refs.something返回“undefined”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!