根据后代的渲染有条件地渲染 React 组件

Conditionally render a React component depending on a descendant's render

我们使用 Reakit dialogs 提示用户在我们的 React 网络应用程序中采取行动。

在某些页面上,我们有与操作相关的特定文本,并希望在对话框中呈现该特定内容。在所有其他页面上,我们希望退回到通用文本。

我们简化的通用页面组件层次结构如下所示:

<BaseLayout>
  ...
</BaseLayout>

对于我们要显示特定文本的页面,

<BaseLayout>
  ...
  <SpecificPage/>
  ...
</BaseLayout>

我们希望发生的事情是:

  1. 在呈现 SpecificPage 组件的页面上,出现带有特定文本的对话框
  2. 在不呈现 SpecificPage 组件的页面上,对话框显示后备通用文本

我们的方法是让 SpecificPage 组件呈现一个带有页面特定文本的对话框,而 BaseLayout 组件呈现一个带有通用回退文本的对话框,但这种方法不是理想情况——在呈现 SpecificPage 对话框之前,用户会看到 BaseLayout 对话框的闪烁。有什么方法可以定义单个组件被组件层次结构中的后代“覆盖”,或者其他方法来实现这种条件渲染?

您可以简单地检查您是否在 BaseLayout 组件中将任何内容呈现为子项,如果没有,您可以回退到通用文本。

这是一个例子。

应用组件

import React from 'react';
import { BaseLayout } from './BaseLayout';

export function App(props) {
  return (
    <div className='App'>
      <BaseLayout>
        <h1>Hello World.</h1>
      </BaseLayout>. // Renders hello world
      <BaseLayout /> // Render generic text
    </div>
  );
}

基本布局组件

import React from 'react';
export function BaseLayout({children}) {
  return (
    <div>
      {children ? children : "Some Generic Text"}
    </div>
  );
}

参见 https://github.com/ariakit/ariakit/discussions/1266#discussioncomment-2617748 for a solution and CodeSandbox that solves this problem well using the Constate 图书馆。