I am trying to write a shorthand version of antd's Select/Option
Instead of using
<Option value='foo'>bar</Option>
I want to use
<Option value='foo' label='bar' />
I wrote following wrapper code:
import { Select } from 'antd'
const Option = (options) => {
const label = options.label
delete options.label
return <Select.Option {...options}>{label}</Select.Option>
}
When I use it in following example
<Select>
<Option value='foo' label='bar'
</Select>
I get
Warning: the children of Select
should be Select.Option
or Select.OptGroup
, instead of Option
.
How can I return my component in a way that antd thinks it is an original Select.Option
?
Due to how original component works, Option
component is dummy component that is never rendered and used as a placeholder for Select
data, wrapping it with another component doesn't do any good.
A possible solution should extend Select
instead:
import {Select as OriginalSelect} from 'antd';
const Option = props => null;
const Select = ({ children, ...props }) => {
children = React.Children(children).map(child => {
if (child.type === Option) {
const {label, ...props} = child.props;
return <OriginalSelect.Option {...props}>{label}</OriginalSelect.Option>;
} else {
return child;
}
});
return <OriginalSelect {...props}>{children}</OriginalSelect>;
};
Also, <Option value='foo' label='bar' />
cannot be considered a shortcut for <Option value='foo'>bar</Option>
because it's of the same length, so if the only purpose of Option
wrapper is to make the code shorter, it's redundant.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.