官网: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>
);
}
}
浙公网安备 33010602011771号