首页 > 解决方案 > 用条件反应打字稿组件集道具

问题描述

我想在定义变量的值时设置组件的道具。以下是我当前的代码。

import Cropper from 'react-easy-crop'
...
interface State {
 ...
  coverFile: File | null;
  ...
}
class Test extends React.PureComponent<Props, State> {
  state = {
    ...
    coverFile: null,
    ...
  };
...
const file = event.target.files;
self.setState({
              coverFile: file[0],
            });

<Cropper
  image={coverFile?coverFile:undefined}
  ...
/>

这是错误信息。

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<CropperProps>): Cropper', gave the following error.
    Type 'null | undefined' is not assignable to type 'string | undefined'.
      Type 'null' is not assignable to type 'string | undefined'.
  Overload 2 of 2, '(props: CropperProps, context?: any): Cropper', gave the following error.
    Type 'null | undefined' is not assignable to type 'string | undefined'.ts(2769)

我怎么解决这个问题?

标签: reactjstypescript

解决方案


这解释了您的错误消息

输入'空| undefined' 不可分配给类型 'string | 不明确的'。

Cropper的图像道具需要一个stringundefined,但你正在传递nullundefined

你初始化coverFilenull?如果是这样,您可以将其设置为以undefined消除错误

更新: 如果你不知道 null 来自哪里,你可以简单地这样做:

<Cropper
  image={coverFile || undefined}
  ...
/>

推荐阅读