<分区>
我有多个重用相同 Prop 的 React 组件,我想知道是否有一种简单的方法可以让我存储和重用这些类型。
例如:
之前:
import * as React from 'react';
interface AnotherButtonProps {
disabled?: boolean;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}
interface SampleButtonProps {
disabled?: boolean;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
title: string;
}
const AnotherButton: React.FC<AnotherButtonProps> = ({ disabled = false, onClick }) => (
<button
disabled={disabled}
onClick={onClick}
type="button"
>
This is another button
</button>
);
const SampleButton: React.FC<SampleButtonProps> = ({ disabled = false, onClick, title }) => (
<button
disabled={disabled}
onClick={onClick}
type="button"
>
{title}
</button>
);
之后:
import * as React from 'react';
interface Disabled {
disabled?: boolean;
}
interface OnClick {
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}
interface Title {
title: string;
}
interface AnotherButtonProps {
disabled?: Disabled;
onClick: OnClick;
}
interface SampleButtonProps {
disabled?: Disabled;
onClick: OnClick;
title: Title;
}
const AnotherButton: React.FC<AnotherButtonProps> = ({ disabled = false, onClick }) => (
<button
disabled={disabled} // get error
onClick={onClick}
type="button"
>
This is another button
</button>
);
const SampleButton: React.FC<SampleButtonProps> = ({ disabled = false, onClick, title }) => (
<button
disabled={disabled}
onClick={onClick}
type="button"
>
{title}
</button>
);
当我尝试重用这些通用接口(interface)时,出现以下错误:
TS2322: Type 'boolean | Disabled' is not an assignable type 'boolean'. Type 'Disabled' is not is not assignable to type 'boolean'.