这个antd库组件在将Javascript转换为Typescript时给我错误

时间:2019-07-08 11:36:14

标签: javascript reactjs typescript

位于handleChange函数中,而setState {imageUrl}

当我只使用javascript时,会显示imagepreview,但在打字稿中显示错误

https://codesandbox.io/s/react-typescript-6yn9v

import { Upload, Icon, message } from "antd";

function getBase64(img: any, callback: any) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file: any) {
  const isJPG = file.type === "image/jpeg";
  if (!isJPG) {
    message.error("You can only upload JPG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJPG && isLt2M;
}

function Avatar() {
  const initialState = {
    loading: false
  };

  const [state, setState] = React.useState(initialState);

  const handleChange = (info: any) => {
    if (info.file.status === "uploading") {
      setState({ ...state, loading: true });
      return;
    }
    if (info.file.status === "done") {
      // Get url from response in real world.
      getBase64(
        info.file.originFileObj,
        (imageUrl: any): any => setState({ ...state, 
            imageUrl, // shows error here but works fine in javascript
             loading: false })
      );
    }
  };

  const uploadButton = (
    <div>
      <Icon type={state.loading ? "loading" : "plus"} />
      <div className="ant-upload-text">Upload</div>
    </div>
  );
  const { imageUrl }: any = state;
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="http://192.168.1.172:9595/upload/multiple"
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
    </Upload>
  );
}

这个antd库组件在将Javascript转换为打字稿时给我错误

1 个答案:

答案 0 :(得分:1)

问题在于React.useState会根据传入的initialState值来推断其管理的状态值的类型。

---
inject: true
to: package.json
after: dependencies
skip_if: lodash
sh: cd <%= cwd %> && yarn install
---
"lodash":"*",

如果在Codesandbox中将state / setState悬停,则可以看到推断的状态类型为

const initialState = {
  loading: false
};
const [state, setState] = React.useState(initialState);

此状态类型中没有imageUrl字段,因此尝试设置该字段是非法的。

有多种方法可以告诉Typescript状态也可以有一个{ loading: boolean } 字段。一种方法是用所需的类型显式注释initialState。另一个方法是对imageUrl调用本身进行注释。

React.useState
interface AvatarState {
  loading: boolean;
  imageUrl?: string;
}
...
const initialState: AvatarState = {
  loading: false
};
const [state, setState] = React.useState(initialState);