有没有办法判断ReactElement是否呈现“null”? [英] Is there a way to tell if ReactElement renders "null"?
本文介绍了有没有办法判断ReactElement是否呈现“null”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的JSX中,我有一个条件渲染逻辑的情况 - 当元素A呈现某些东西时(它的 render()
函数返回 null
),然后渲染元素B,就在元素A的上方。
In my JSX, I have a case of a conditional rendering logic - when element A renders something (it's render()
function returns something other than null
), then also render element B, just above the element A.
代码示例(简化)如下所示:
Code example (simplified) would look like this:
function render() {
let elemA = (<ElementA someProp={this.someVar} />);
if (elemA.isNull()) {
return (
<div>
{ ...someElements }
</div>
);
}
return (
<div>
{ ...someElements }
<ElementB />
{ elemA }
</div>
);
}
所以我的问题是 - 有什么办法吗?有 elemA.isNull()
检查?
So my question is - Is there any way to have the elemA.isNull()
check?
推荐答案
不,没有办法确定孩子将使用React渲染什么。执行此操作的标准方法是公开一些实用函数,该函数说明A是否将呈现。
No, there's no way to determine what a child will render using React. The standard way to do this is to expose some utility function that says whether A will render.
类似于:
if (AUtils.isStoryValid(story)) {
return <A story={story} />;
} else {
return <B story={story} />;
}
这篇关于有没有办法判断ReactElement是否呈现“null”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文