假设我有四个组件,我想根据type
使用 daggy 的道具有条件地渲染它们:
在此示例中, type
prop 值可以是字符串a
, b
,c
或d
这是一个有效的代码框示例
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 的情况下以类似的方式实现条件渲染,它也可以解决我的问题。
有什么建议么?