我一直试图弄清楚如何包装一个ant-design表单组件。我有几个Select
具有相同的选项,因此我想创建一个SelectWrapper
(请参阅下面的代码段)。不幸的是,antd的形式似乎并不喜欢这样,而且
createBaseForm.js:98 Uncaught TypeError:无法读取属性' 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>
);
}
完整的例子(要求传播宝贝)
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
以查看问题
答案 0 :(得分:1)
在https://github.com/ant-design/ant-design/issues/5700
中解决表格需要控件的参考,但功能组件没有参考。
解决方案是使用基于类的包装器组件来代替基于功能的组件。
答案 1 :(得分:0)
如何包装antd组件?传播爱与道具!!!
import { Select as AntSelect} from 'antd';
const Select = (props) => {
return (<AntSelect {...props} >{props.children}</AntSelect>)
}