简体   繁体   English

如何设置/伪造组件的proptype

[英]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.OptionSelect.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM