我有一个有条件地呈现几个子组件的react组件。简化的代码只是:
render(): {
const component1 = condition ? renderComponent2() : null;
const component2 = renderComponent2();
return (
<div>
{component1}
{component2}
</div>
);
}
问题是component2
每当condition
发生变化时都会被破坏和重新渲染。我试图阻止这种情况并保留原始元素。我尝试添加一个key
to component2
,但没有运气。
[编辑] 即使component1
始终存在,也会发生这种情况,我更改其上的标志以使用 CSS 隐藏或不隐藏它:/