官網:https://ant.design/docs/react/use-with-create-react-app-cn
1、安裝:antd
npm install antd@^3.26.13 -S
2.按需引入antd, 安裝 npm add react-app-rewired customize-cra
/* package.json */ "scripts": { - "start": "react-scripts start", + "start": "react-app-rewired start", - "build": "react-scripts build", + "build": "react-app-rewired build", - "test": "react-scripts test", + "test": "react-app-rewired test", }
3.根目錄下創建config-overrides.js
const { addWebpackAlias, addLessLoader, fixBabelImports, override, addDecoratorsLegacy } = require('customize-cra') const path = require('path') module.exports = override( // @ 修飾器 addDecoratorsLegacy(), fixBabelImports('import', { libraryName: 'antd', libraryDirectory: 'es', // 支持 less sass stylus style: true, }), // 支持 antd 主題定制 addLessLoader({ javascriptEnabled: true, }), // 別名 addWebpackAlias({ '@': path.resolve(__dirname, 'src'), '@@': path.resolve(__dirname, 'src/components'), }) )
這樣就可以正常使用了。下面舉個form的例子
import React from 'react' import { Form, Input, Button, } from 'antd'; //export default @Form.create() //使用@修飾器
export default @Form.create({ //這里就順便把表單回填也寫下算了。
mapPropsToFields(props) {
return {
username: Form.createFormField({
value: 22, //
})
}
}
})
class NormalLoginForm extends React.Component { handleSubmit = e => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log('Received values of form: ', values); } }); }; render() { const { getFieldDecorator } = this.props.form; return ( <Form onSubmit={this.handleSubmit} className="login-form"> <Form.Item> {getFieldDecorator('username', { rules: [{ required: true, message: 'Please input your username!' }], })( <Input placeholder="Username" />, )} </Form.Item> <Form.Item> <Button type="primary" htmlType="submit" className="login-form-button"> Log in </Button> </Form.Item> </Form> ); } }