[英]How can I set/fake the proptype of a component
I am trying to write a shorthand version of antd's Select/Option 我正在尝试编写antd的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
. 警告:
Select
的子项应为Select.Option
或Select.OptGroup
,而不是Option
。
How can I return my component in a way that antd thinks it is an original Select.Option
? 如何以antd认为它是原始
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. 由于原始组件的工作原理,
Option
组件是虚拟组件,永远不会被渲染并用作Select
数据的占位符,用另一个组件包装它并没有任何好处。
A possible solution should extend Select
instead: 一个可能的解决方案应该扩展
Select
:
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. 此外,
<Option value='foo' label='bar' />
不能被视为<Option value='foo'>bar</Option>
的快捷方式,因为它具有相同的长度,因此如果Option
包装的唯一目的是为了缩短代码,这是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.