【发布时间】:2021-08-02 21:39:25
【问题描述】:
所以我试图在我正在构建的 React Native 应用程序中组合一些组件,以便它们可以共享逻辑和样式并使其更易于维护。现在,它们之间的唯一区别是它们为 props 扩展的接口和渲染组件的名称。以下是我想要做的简化形式:
interface ISharedInputProps {
label: string;
errorText?: string | null;
isPassword?: boolean;
hasTextRight?: boolean;
}
export interface IInputProps extends React.ComponentProps<typeof TextInput>, ISharedInputProps {
inputType: 'input';
}
export interface IMaskedInputProps extends React.ComponentProps<typeof MaskedTextInput>, ISharedInputProps {
inputType: 'masked';
}
export interface ICurrencyInputProps extends React.ComponentProps<typeof CurrencyInput>, ISharedInputProps {
inputType: 'currency';
}
const Input: React.FC<IInputProps | IMaskedInputProps | ICurrencyInputProps> = ({
inputType,
...props
}) => {
// Component logic here
return (
// Shared wrapping UI here
{ inputType === 'input' && <TextInput {...props}/> }
{ inputType === 'masked' && <MaskedTextInput {...props}/> }
{ inputType === 'currency' && <CurrencyInput {...props}/> }
// Shared wrapping UI here
)
};
export default Input;
但是,一旦我进入 inputType 条件,编译器就会抛出一个错误,因为每种类型之间存在冲突,没有兼容的值(即:“Type '(text: string, rawText: string) => void'不可分配给类型“(文本:字符串)=> void”。输入组件声明上的实际联合类型似乎不会引发错误,只是在初始化内部组件时。删除 IMaskedInputProps 或 ICurrencyInputProps 有效,所以他们之间似乎正在发生冲突。
我的理解是,如果我将 inputType 设置为预定义值(即:'input'),它会自动将 IMaskedInputProps 接口分配给组件,但情况似乎并非如此。有没有办法做我想做的事,而不仅仅是将输入类型更改为React.FC<any> 并在 UI 本身中放置一堆检查?
【问题讨论】:
-
inputTypeforCurrencyInput应该是currency对吧?您已将其设置为input。 -
@JeffMercado 啊,哎呀,我的错。固定的!它就在应用程序上:P
标签: reactjs typescript