问题描述
假设我有四个组件,我想根据 type
道具使用 daggy 有条件地渲染它们:
在本例中,type
属性值可以是字符串 a
、b
、c
或 d
here 是一个有效的代码和框示例
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 />,});
};
这按预期工作,但似乎有点复杂,我觉得我在这里遗漏了一些东西,我已经阅读了 documentation 但我无法真正理解如何将其应用于这个简单的示例.
我在互联网上找到的示例对于我想要实现的目标来说太复杂了,这只是根据道具使用 daggy 渲染组件。
这是一个使用 daggy 的条件渲染的 example,不幸的是它使用了一个额外的库来实现这一点,而且它似乎比我的例子更复杂。
如果有另一种方法可以在不使用 daggy 的情况下以类似的方式实现条件渲染,它也可以解决我的问题。
有什么建议吗?
解决方法
您根本不需要使用 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} />;
};