0

假设我有四个组件,我想根据type使用 daggy 的道具有条件地渲染它们:

在此示例中, typeprop 值可以是字符串a, b,cd

是一个有效的代码框示例

import daggy from 'daggy';
import { componentA, componentB, componentC, componentD } from './components';

const UI = daggy.taggedSum('UI', {
  A: [],
  B: [],
  C: [],
  D: [],
});

const VIEWS = {
  a: UI.A,
  b: UI.B,
  c: UI.C,
  d: UI.D,
};

const getView = (type) => VIEWS[type];

export const Component = ({ type }) => {
  const view = getView(type);
  return view.cata({
    A: () => <ComponentA />,
    B: () => <ComponentB />,
    C: () => <ComponentC />,
    D: () => <ComponentD />,
  });
};

这按预期工作,但似乎有点复杂,我觉得我在这里遗漏了一些东西,我已经阅读了文档,但我无法真正理解如何将它应用于这个简单的示例。

我在互联网上找到的示例对于我想要实现的目标来说太复杂了,这只是根据道具使用 daggy 渲染组件。

这是一个使用 daggy 进行条件渲染的示例,不幸的是它使用了一个额外的库来实现这一点,它似乎比我的示例更复杂。

如果有另一种方法可以在不使用 daggy 的情况下以类似的方式实现条件渲染,它也可以解决我的问题。

有什么建议么?

4

1 回答 1

1

你根本不需要使用daggy!您只需要使用类型映射每个组件并渲染它。

尝试这个:

import * as React from "react";

import { ComponentA } from "./ComponentA";
import { ComponentB } from "./ComponentB";
import { ComponentC } from "./ComponentC";
import { ComponentD } from "./ComponentD";

type ComponentProps = {
 type: string;
};

const componentVariants = {
  a: ComponentA,
  b: ComponentB,
  c: ComponentC,
  d: ComponentD
};


export const Component = ({ type, ...other }: ComponentProps) => {
  const Component = componentVariants[type];
  return <Component {...other} />;
};
于 2021-04-24T09:50:04.677 回答