2

我一直在试图弄清楚如何包装一个 ant-design 表单组件。我有几个Selects 会有相同的选项,所以我想创建一个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-issuenpm start查看问题

4

2 回答 2

2

如何包装antd组件?传播爱和道具!!!

import { Select as AntSelect} from 'antd'; 

const Select = (props) => {
    return (<AntSelect {...props} >{props.children}</AntSelect>)
}
于 2020-06-23T06:43:45.033 回答
1

https://github.com/ant-design/ant-design/issues/5700中解决

表单需要控件的引用,但功能组件没有引用。

解决方案是使用基于类的包装器组件代替基于功能的包装器组件。

于 2017-04-11T18:08:01.670 回答