Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【长期】TypeScript 开发常见问题 #2

Open
zhongxia245 opened this issue Aug 3, 2019 · 1 comment
Open

【长期】TypeScript 开发常见问题 #2

zhongxia245 opened this issue Aug 3, 2019 · 1 comment

Comments

@zhongxia245
Copy link
Owner

zhongxia245 commented Aug 3, 2019

React组件使用 TypeScript 编写时,组件属性类型声明问题

刚开始使用 TS,因此记下该问题

现象

Property 'welcome' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }>...'.

原因

在 React组件 中使用TypeScript ,需要对 React 的属性进行声明(指定有哪些属性,属性什么类型),否则 Tslint 会会报错。

import * as React from "react";
import ControlArea from "./ControlArea";

export class Layout extends React.Component {
  public render() {
   const { welcome } = this.props
    return (
       <div>{welcome}</div>
    );
  }
}

解决方案

为 React.Component 添加一个属性类型接口即可

interface IControlAreaProps {
  welcome?: any
}

export default class ControlArea extends React.Component<IControlAreaProps> {
  // Your ControlArea code
}

参考地址:https://stackoverflow.com/questions/48890795/react-typescript-property-does-not-exist-on-type-intrinsicattributes-intrins

@zhongxia245
Copy link
Owner Author

TypeScript 如何给 Form.create 的组件,添加属性声明

现象

AntdForm.create()(App) 创建的组件,TS 给 App 组件添加属性声明了,但是 TSLint 还是报错。

解决方案

import { Form } from 'antd';
import { FormComponentProps } from 'antd/lib/form';

interface UserFormProps extends FormComponentProps {
  age: number;
  name: string;
}

class UserForm extends React.Component<UserFormProps, any> {
  // ...
}

const App = Form.create<UserFormProps>({
  // ...
})(UserForm);

参考文章

https://blog.csdn.net/m0_37148591/article/details/91537676

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant