【问题标题】:Limit child components in a react component限制反应组件中的子组件
【发布时间】:2019-10-31 22:05:59
【问题描述】:

我有一个问题,我不确定是否可能。 这是一个示例代码。 我有一个组件,我希望他们每次使用我的组件和一个孩子 它应该只接受特定的组件。

例如:

<tableComponent>
   <tableHeaderComponent/>
   <tableHeaderComponent/>
   <tableHeaderComponent/>
</tableComponent>
but for this type it should not be accepted
<tableComponent>
   <th>blah</th>
   <th>blah2</th>
   <yourowncomponent/>
</tableComponent>

谢谢, 乒乓球

【问题讨论】:

标签: reactjs


【解决方案1】:

displayName 分配给您要允许的组件,并在父组件内部检查子组件是否具有允许的displayName

const Good = () => <h1>Good</h1>;

Good.displayName = "Good";

const Bad = () => <h1>Bad</h1>;

const WithGoodOnly = ({ children }) => {
  let allowed;
  if (Array.isArray(children)) {
    allowed = children.every(child => child.type.displayName === "Good");
  } else {
    allowed = children.type.displayName === "Good";
  }

  return allowed ? <div>{children}</div> : null;
};

渲染

const App = () => (
  <WithGoodOnly>
    <Good />
  </WithGoodOnly>
);

渲染

const App = () => (
  <WithGoodOnly>
    <Good />
    <Good />
  </WithGoodOnly>
);

未渲染

const App = () => (
  <WithGoodOnly>
    <Good />
    <Bad />
  </WithGoodOnly>
);

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 2021-04-27
    • 1970-01-01
    • 2020-09-17
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多