如何在 React(使用 TypeScript)中创建具有灵活操作的自定义操作栏?

发布于 2025-01-17 09:07:34 字数 653 浏览 4 评论 0原文

我想创建一个具有灵活动作的自定义动作栏,可以通过道具设置或类似的操作。

这就是我实施它的方式(并且它的工作原理),但是我想知道是否有更好或更清洁的React方法(使用Typescript)。

特别是当动作随着时间而增加时。然后,我将不得不添加更多的布尔人,最终会使事情令人困惑。

type CustomBarProps = {
    withButton: boolean,
    withCheckbox: boolean,
    withRadio: boolean,
}

export const CustomBar = ({
    withButton = false,
    withCheckbox = false,
    withRadio = false,
}: CustomBarProps) => {
    const features: JSX.Element[] = [
        withButton && <Button />,
        withCheckbox && <Checkbox />,
        withRadio && <Radio />,
    ]
    return <Bar features={features} />
}

I would like to create a custom action bar with flexible actions that can be set via props or similar.

This is how I implemented it (and it's working like expected), but I'm wondering if there's a better or cleaner way in React (with TypeScript).

Especially when the actions increase over time. Then I would have to add more booleans that would eventually make things confusing.

type CustomBarProps = {
    withButton: boolean,
    withCheckbox: boolean,
    withRadio: boolean,
}

export const CustomBar = ({
    withButton = false,
    withCheckbox = false,
    withRadio = false,
}: CustomBarProps) => {
    const features: JSX.Element[] = [
        withButton && <Button />,
        withCheckbox && <Checkbox />,
        withRadio && <Radio />,
    ]
    return <Bar features={features} />
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野の 2025-01-24 09:07:34

是的,您不需要明确定义每个道具必须是错误的,您也可以这样做

type CustomBarProps = {
  Button?: boolean;
  Checkbox?: boolean;
  Radio?: boolean;
};

export const CustomBar: React.FC<CustomBarProps> = ({ Button, Checkbox, Radio }) => {
  const features = [Button && <Button />, Checkbox && <Checkbox />, Radio && <Radio />];
  return <Bar features={features} />;
};

yeah you don't need to explicitly define each prop has to be false you can also do it like this

type CustomBarProps = {
  Button?: boolean;
  Checkbox?: boolean;
  Radio?: boolean;
};

export const CustomBar: React.FC<CustomBarProps> = ({ Button, Checkbox, Radio }) => {
  const features = [Button && <Button />, Checkbox && <Checkbox />, Radio && <Radio />];
  return <Bar features={features} />;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文