根据组件的返回值有条件地安装组件

问题描述 投票:0回答:2

有没有一种方法可以检查组件是否为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 />
reactjs
2个回答
1
投票
const ComponentC = () => {
    return shouldRender ? <ComponentA /> : <ComponentB />;
}

1
投票

AFAIK,这是不可能的。您将必须有条件地在外部组件上进行渲染:

const ComponentD = () => {
  return shouldRender ? <ComponentA shouldRender={true} /> : <ComponentB />;
}

或渲染这两个组件,但赋予它们shouldRender属性,因为实际上不显示组件渲染为null:

const ComponentD = () => {
  return (
    <>
      <ComponentA shouldRender={shouldRender} />
      <ComponentB shouldRender={!shouldRender} />
    </>
  );
}

编辑:如果ComponentA的渲染条件是否在组件内部,并且足够复杂以至于您不想复制它,则可能应将其外部化,并由组件A和B都使用。 >

© www.soinside.com 2019 - 2024. All rights reserved.