这是 HOC,我有以下错误:
Type 'Pick, "children" | Exclude> & { ...; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'
Type 'Pick, "children" | Exclude> & { ...; }' is not assignable to type 'P'.
'Pick, "children" | Exclude> & { ...; }' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint 'TextInputProps'.
怎么修?
import { View, ViewStyle, StyleProp, NativeSyntheticEvent, TextStyle, TextInputProps } from 'react-native';
type Props = {
styleWrapper?: StyleProp<ViewStyle>;
style?: StyleProp<TextStyle>;
title?: string;
value?: string;
onFocus?: (e: NativeSyntheticEvent<any>) => void;
onBlur?: (e: NativeSyntheticEvent<any>) => void;
onChange?: (text: string) => void;
onReset?: () => void;
withReset?: boolean;
};
export const withInputWrapper = <P extends TextInputProps = TextInputProps>(
InputComponent: React.ComponentType<P>
): React.FC<P & Props> => {
return ({ styleWrapper, style, title, value, onFocus, onBlur, onChange, onReset, withReset = true, ...props }) => {
const onFocusHandler = ...
const onBlurHandler = ...
const onChangeHandler = ...
return (
<View style={styleWrapper}>
<View style={s.inputWrapper}>
<InputComponent // <-- here
{...props}
onChange={onChangeHandler}
value={value}
style={style}
onBlur={onBlurHandler}
onFocus={onFocusHandler}
/>
</View>
</View>
);
};
};
最佳答案
这是当您达到 TS 可以对具有条件和映射类型的泛型类型参数进行推理的限制时的情况之一。虽然 props
可能看起来很明显 P
,这对编译器来说并不明显。编译器将使用 Omit
输入 props
它使用映射类型和条件类型从给定类型中删除一些键。所以 props 将被输入为 Omit<P & Props, keyof Props>
.这可能看起来很明显 P
,但 TS 不能遵循条件类型,只要它们仍有未解析的类型参数。这意味着,就 TS 而言 Omit<P & Props, keyof Props>
和 P
是不同的类型。
这里唯一的解决方案是使用类型断言:
export const withInputWrapper = <P extends TextInputProps = TextInputProps>(
InputComponent: React.ComponentType<P>
): React.FC<P & Props> => {
return ({ styleWrapper, style, title, value, onFocus, onBlur, onChange, onReset, withReset = true, ...props }) => {
const onFocusHandler = () => {}
const onBlurHandler = () => {}
const onChangeHandler = () => {}
return (
<View style={styleWrapper}>
<View>
<InputComponent // <-- here
{...props as P}
onChange={onChangeHandler}
value={value}
style={style}
onBlur={onBlurHandler}
onFocus={onFocusHandler}
/>
</View>
</View>
);
};
};
Playground Link
关于reactjs - 可分配给 'P' 类型的约束,但 'P' 可以用约束 'TextInputProps' 的不同子类型实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60735375/