& { ...; }' is not assignable to type 'IntrinsicAtt-6ren">
gpt4 book ai didi

reactjs - 可分配给 'P' 类型的约束,但 'P' 可以用约束 'TextInputProps' 的不同子类型实例化

转载 作者:行者123 更新时间:2023-12-04 11:45:12 28 4
gpt4 key购买 nike

这是 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com