一种简洁的条件渲染组件的方法

2025-06-08

一种简洁的条件渲染组件的方法

今天,我想分享一种使用 React 时有条件渲染子组件的简洁方法。非常简单。

现场演示:
https://codesandbox.io/s/if-component-demo-9iipl?file= /src/App.js


function App(){
  // ...
  return <div>
      {someCondition?
      <SomeChildA>
        <div>Some Contents</div>
        <div>Some Contents</div>
        <div>Some Contents</div>
      </SomeChildA>
      : 
      <SomeChildB>
        <div>Some Contents</div>
        <div>Some Contents</div>
        <div>Some Contents</div>
      </SomeChildB>}
    </div>
}

Enter fullscreen mode Exit fullscreen mode


function App(){
  // ...
  return <div>
      <If condition={someCondition}>
        <SomeChildA>
          <div>Some Contents</div>
          <div>Some Contents</div>
          <div>Some Contents</div>
        </SomeChildA>
      </If>
      <If condition={!someCondition}>
        <SomeChildB>
          <div>Some Contents</div>
          <div>Some Contents</div>
          <If condition={someOtherCondition}>
            <NestExample/>
          </If>
          <div>Some Contents</div>
        </SomeChildB>
      </If>
    </div>
}

Enter fullscreen mode Exit fullscreen mode

<If/> 组件

function If(props) {
    return props.condition ? <>{props.children}</> : null;
}
Enter fullscreen mode Exit fullscreen mode

感谢阅读!祝您拥有美好的一天!

鏂囩珷鏉ユ簮锛�https://dev.to/anxiny/a-clean-way-to-conditionally-render-components-109i
PREV
NextJS 中的页面过渡效果
NEXT
像专业人士一样过滤数组