初始化端項目
通過react的腳手架create-react-app初始化一個前端項目:
//如果沒有create-react-app,會直接先下載一個
npx create-react-app crowller-front --template typescript --use-npm
初始化完成之后,精簡一下項目目錄,并編寫login頁面。
login頁面
- 安裝antd:
npm install antd@3.26.18 -S - 將表單示例進(jìn)行精簡,并粘貼進(jìn)項目
import React,{ Component } from 'react'
import { Form, Icon, Input, Button, Checkbox } from 'antd';
import './login.css'
interface Props{
form:any
}
class NormalLoginForm extends React.Component<Props> {
handleSubmit = (e:any) => {
e.preventDefault();
this.props.form.validateFields((err:any, values:any) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<div className="login-wrapper">
<Form onSubmit={this.handleSubmit} className="login-form">
<Form.Item>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Password"
/>,
)}
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className="login-form-button">
Log in
</Button>
</Form.Item>
</Form>
</div>
);
}
}
const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(NormalLoginForm);
export default WrappedNormalLoginForm;
效果:

image.png
對form組件的類型進(jìn)行定義
按住command 點(diǎn)進(jìn)源代碼包進(jìn)行類型的查看:

image.png
- 先找到from的類型
從類型文件中可以看出,WrappedFormUtils這個類型具備的方法正是form所具備的
image.png - 將這個類型引入
import {WrappedFormUtils} from 'antd/lib/form/Form'
-
找validateCallback的類型
image.png
得出errors是一個any,而values是另一個泛型
而這個V是FormUtils這個類型所接受的
image.png
這樣以來只要這么編寫類型即可:
interface FormProps{
password:string;
}
interface Props{
form:WrappedFormUtils<FormProps>
}
class NormalLoginForm extends Component<Props> {
handleSubmit = (e:any) => {
e.preventDefault();
this.props.form.validateFields((err:any, values:FormProps) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
這樣登陸頁面的組件就完成的差不多了


