我一直在试图弄清楚如何包装一个 ant-design 表单组件。我有几个Select
s 会有相同的选项,所以我想创建一个SelectWrapper
(见下面的片段)。不幸的是,antd 的表单似乎不喜欢这样,并且会出错
createBaseForm.js:98 未捕获类型错误:无法读取未定义的属性“onChange”
尽管我通过表单道具传递给Select
.
function ReusableCountrySelect({countries, ...props}) {
return (
<Select
{...props}
>
{
countries.map(c => (
<Select.Option
value={c.id}
key={c.id}
>{c.name}</Select.Option>
))
}
</Select>
);
}
完整示例(需要 babel 进行传播)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const mountNode = document.getElementById('root');
import {
Form, Select, Button
} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
function ReusableCountrySelect({countries, ...props}) {
return (
<Select
{...props}
>
{
countries.map(c => (
<Select.Option
value={c.id}
key={c.id}
>{c.name}</Select.Option>
))
}
</Select>
);
}
class Demo 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}>
<FormItem
label="Select Country"
hasFeedback
>
{getFieldDecorator('select', {
rules: [
{ required: true, message: 'Please select your country!' },
],
})(
<ReusableCountrySelect
countries={[
{name: 'china', id: 'china'},
{name: 'india', id: 'india'},
{name: 'britain', id: 'britain'}
]}
placeholder="Please select a country"
/>
)}
</FormItem>
<FormItem
wrapperCol={{ span: 12, offset: 6 }}
>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
);
}
}
const WrappedDemo = Form.create()(Demo);
ReactDOM.render(<WrappedDemo />, mountNode);
克隆https://github.com/megawac/antd-form-issue并npm start
查看问题