0

我正在使用带有打字稿的本机反应,我想从状态更新我的样式属性。但这给了我错误。

const [VerifiedCheck, setIsVerifiedCheck] = useState("flex");

<View style={{display: VerifiedCheck}}>
  <Icon name={'check-circle'} size={24} color={'green'} />
</View>

我收到错误style

No overload matches this call.
  Overload 1 of 2, '(props: ViewProps | Readonly<ViewProps>): View', gave the following error.
    Type '{ display: string; }' is not assignable to type 'StyleProp<ViewStyle>'.
      Types of property 'display' are incompatible.
        Type 'string' is not assignable to type '"none" | "flex" | undefined'.
  Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error.
    Type '{ display: string; }' is not assignable to type 'StyleProp<ViewStyle>'.
      Types of property 'display' are incompatible.
        Type 'string' is not assignable to type '"none" | "flex" | undefined'.ts(2769)
index.d.ts(2522, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'
index.d.ts(2522, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'
4

1 回答 1

0

正如错误所说,

Type 'string' is not assignable to type 
'"none" | "flex" | undefined'.ts(2769)

问题是当你说,

const [VerifiedCheck, setIsVerifiedCheck] = useState("flex");

推断的类型verifiedCheckstring最常见的情况。例如,看到这个:

const [title, setTitle] = useState("default title");

将 typescripttitle视为字符串是很有意义的。所以,我认为,如果你明确告诉 typescript 可能的类型,它就不会再打扰你了。像这样:

const [VerifiedCheck, setIsVerifiedCheck] = useState<"none" | "flex" | undefined>("flex");

<View style={{display: VerifiedCheck}}>
  <Icon name={'check-circle'} size={24} color={'green'} />
</View>
于 2021-06-30T11:56:37.057 回答