有没有一种方法可以检查组件是否为null?
const ComponentA = ({ shouldRender }) => {
if(!shouldRender){
return null;
}
return <div>Foo</div>
}
const ComponentB = () => <div>Bar</div>
// I want this component to render ComponentA
const ComponentC = () => {
return <ComponentA shouldRender /> || <ComponentB />;
}
// I want this component to render ComponentB, as ComponentA returns null
const ComponentD = () => {
return <ComponentA shouldRender={false} /> || <ComponentB />;
}
按预期渲染<div>Foo</div>
<ComponentC />
我希望它呈现<div>Bar</div>
,但已安装ComponentA并呈现null
<ComponentD />
const ComponentC = () => {
return shouldRender ? <ComponentA /> : <ComponentB />;
}
AFAIK,这是不可能的。您将必须有条件地在外部组件上进行渲染:
const ComponentD = () => {
return shouldRender ? <ComponentA shouldRender={true} /> : <ComponentB />;
}
或渲染这两个组件,但赋予它们shouldRender
属性,因为实际上不显示组件渲染为null:
const ComponentD = () => {
return (
<>
<ComponentA shouldRender={shouldRender} />
<ComponentB shouldRender={!shouldRender} />
</>
);
}
编辑:如果ComponentA
的渲染条件是否在组件内部,并且足够复杂以至于您不想复制它,则可能应将其外部化,并由组件A和B都使用。 >