[note] Ant Design
內容已過時
本文涵蓋的是 Ant Design v3 的 API(如 Form.create()、getFieldDecorator),這些 API 在 Ant Design v4(2020 年 2 月)中已被完全移除。目前最新版為 v5,使用 Form.useForm() Hook 和 CSS-in-JS(不再需要手動引入 CSS 或使用 babel-plugin-import)。
安裝與使用
安裝 Ant Design
$ npm install antd --save
設定 webpack 內的 babel-loader
$ npm install babel-plugin-import --save-dev
在這裡設定 plugins 可以讓我們在使用到該元件的時候,Babel 會自動載入相關的 CSS :
// webpack.config.js
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }], // `style: true` for less
],
},
},
},
];
如果沒有在 webpack babel-loader 這裡設定的話,需要手動載入 CSS:
import 'antd/dist/antd.css'; // 載入所有 CSS
import 'antd/lib/date-picker/style/css'; // 載入特定模組的 CSS
使用 AntdDesign
import { DatePicker } from 'antd';
const root = ReactDOM.createRoot(mountNode);
root.render(<DatePicker />);
Form
Form.create():需要先使用Form.create()(<Component>)才能使用this.props.form取得 Antd 提供的 Form 方法。form.getFieldDecorator:當欄位有使用getFieldDecorator()做雙向綁定的話,資料就會被存在 Form 元件的狀態中,不需要再另外存一份在 state 中。options.initialValue:一般設定欄位預設值的方式。Form.create({ mapPropsToFields }):當有使用mapPropsToFields並搭配Form.createFormField方法時,不需要定義options.initialValue即會自動將欄位的資料帶入。
通常
mapPropsToFields和onFieldsChange會搭配 Redux 使用,可參考 rc-form@2.4.3。
options.initialValue 和 mapPropsToFields
- 若有使用
mapPropsToFields則在getFieldDecorator即可不去定義options.initialValue。 - 當「沒有」使用
mapPropsToFields時,則需要在getFieldDecorator中options.initialValue中將 props 的資料傳入。 - 如果「同時」使用了
mapPropsToFields和options.initialValue則會以mapPropsToFields中Form.createFormField的值為主。