简体   繁体   English

React TypeScript ref在条件渲染中返回null

[英]React typescript ref return null in conditional rendering

I want to use React refs, it works fine in static rendering, eg: 我想使用React refs,它在静态渲染中很好用,例如:

<footer ref="ftr"></footer>

But, not in conditional rendering, eg: 但是, 不是在条件渲染中,例如:

{footer ?
    <footer ref="ftr"></footer>
: null}

When I called ReactDOM.findDOMNode(this.refs.ftr); 当我调用ReactDOM.findDOMNode(this.refs.ftr); , the first way returned the element (fine) but the second returned me undefined . ,第一种方法返回元素 (fine),但是第二种方法返回undefined

How to do the right way in conditional rendering? 如何在条件渲染中做正确的选择? Any answer would be appreciated. 任何答案将不胜感激。

You should not use string refs as written in the docs : 您不应使用docs中编写的字符串引用:

We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases 我们建议您不要这样做,因为字符串引用存在一些问题,被认为是旧的,并且很可能在将来的发行版中被删除。

You can do this: 你可以这样做:

let footerElement: HTMLElement | null = null;
...
{footer ?
    <footer ref={ el => footerElement = el }></footer>
: null}
...
if (footerElement != null) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM