【问题标题】:Deciding Runtime Props Typescript决定运行时道具打字稿
【发布时间】:2020-01-17 16:30:03
【问题描述】:

我正在使用打字稿在react.js 中创建一个组件。我被困了一段时间,想知道如何让prop 强制要求两者之一。我正在创建一个Label 组件。它应该在 props 中收到 icontitle。我过去传递道具的方式是:

import React, { forwardRef } from 'react';
import clsx from 'clsx';

export interface LabelProps{
  className?: string;
  onClick?: () => void;
  icon: string,
  title: string
}

export const Label = forwardRef<HTMLDivElement, LabelProps>(function(
  { className, onClick, icon, title },
  ref,
) {
  return (
    <div className={clsx(className, 'label')} onClick={onClick} ref={ref}>
      // My Way to display thing's
    </div>
  );
});

export default Label;

现在,我知道我可以分别在 props 和 render 中检查 icontitle 的值。但我希望打字稿不允许我通过它们并显示错误。我想将此组件用作:

<Label icon={icon} />

<Label title={title} />

但不是如下。打字稿应该抱怨这个:

<Label icon={icon} title={title} />

你能告诉我实现这一目标的方法吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您可以尝试这样做。 这有助于使 Prop (title, icon) 相互依赖,或者根本没有 Prop (title, icon)。

    export interface BaseLabelProps extends HTMLAttributes<HTMLLabelElement> {
      className?: string;
    }
    
    interface LabelWithIconProps extends BaseLabelProps {
      icon?: string;
      title?: never;
    }
    
    interface LabelWithoutIconProps extends BaseLabelProps {
      icon?: never;
      title?: string;
    }
    
    export type LabelProps = LabelWithoutIconProps | LabelWithIconProps;
    

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2021-04-30
      • 2018-06-30
      • 2021-07-11
      • 1970-01-01
      • 2018-06-04
      相关资源
      最近更新 更多