【问题标题】:How to use daggy for conditional rendering in React如何在 React 中使用 daggy 进行条件渲染
【发布时间】:2021-07-18 02:14:50
【问题描述】:

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

在此示例中,type 属性值可以是字符串 abcd

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 和 React 完成什么?
  • 我想使用 daggy 和 React 有条件地渲染一个组件,所以给定一个 prop 值,它将渲染一个或另一个组件。
  • 但是看起来 daggy 在这里并不是很有帮助。如您所见,您需要类似于枚举的东西(想想使用 A、B、C 或 D),但这似乎不是 daggy 明确支持的东西。

标签: reactjs conditional-rendering catamorphism fantasyland


【解决方案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} />;
};

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 2019-08-18
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2018-10-02
    • 2021-06-13
    相关资源
    最近更新 更多