【发布时间】:2020-01-17 16:30:03
【问题描述】:
我正在使用打字稿在react.js 中创建一个组件。我被困了一段时间,想知道如何让prop 强制要求两者之一。我正在创建一个Label 组件。它应该在 props 中收到 icon 或 title。我过去传递道具的方式是:
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 中检查 icon 和 title 的值。但我希望打字稿不允许我通过它们并显示错误。我想将此组件用作:
<Label icon={icon} />
或
<Label title={title} />
但不是如下。打字稿应该抱怨这个:
<Label icon={icon} title={title} />
你能告诉我实现这一目标的方法吗?
【问题讨论】:
标签: reactjs typescript