我一直在试图弄清楚如何包装 ant-design 表单组件。我有几个具有相同选项的 Select,因此我想创建一个 SelectWrapper(请参阅下面的代码片段)。不幸的是,antd 的表单似乎不喜欢这个,并且会出错
createBaseForm.js:98 Uncaught TypeError: Cannot read property 'onChange' of undefined
尽管我将表单 Prop 传递给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
查看问题
最佳答案
如何包装antd组件?传播爱和 Prop !!!
import { Select as AntSelect} from 'antd';
const Select = (props) => {
return (<AntSelect {...props} >{props.children}</AntSelect>)
}
关于javascript - 包装 Ant-Design 表单组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43286302/