首页 > 解决方案 > 是否可以将组件作为字符串道具传递?(使用组件库)

问题描述

我正在使用我的雇主提供的“可重用组件库”来呈现复选框。复选框组件的代码是:

const CheckboxInput = (props) => {

 const { classNames, label, ...attrs } = props;
  return (
    <label className="foo">
      <Input
        { ...attrs }
        classNames={classnames(
          classNames,
          'bar')}
        type="checkbox"
      />
      <span className="foo"></span>
      {label &&
      <span className="foo">
        {label}
      </span>
      }
    </label>
  );
};

CheckboxInput.propTypes = {
  label: PropTypes.string,
  classNames: PropTypes.string
};

我希望标签的一部分为灰色,其余部分具有默认样式。我能够使它与以下任一实现一起使用:

<CheckboxInput
  label={<span>My unstyled string <span style={{ color: 'grey' }}>{'My String that I want to be grey'}</span></span>}
  checked={isChecked}
  onChange={ () => handleChange(e.target.value) }
/>

或者

<CheckboxInput
  label={['My unstyled string', <span style={{ color: 'grey' }}>{'My String that I want to be grey'}</span>]}
  checked={isChecked}
  onChange={ () => handleChange(e.target.value) }
/>

不幸的是,第一个实现引发了一个控制台错误:Invalid prop `label` of type `object` supplied to `CheckboxInput`, expected `string`.

第二个实现给了我一个控制台错误:Invalid prop `label` of type `array` supplied to `CheckboxInput`, expected `string`.。除了这个错误:Each child in an array or iterator should have a unique "key" prop.

有没有办法在不破坏性地编辑 CheckboxInput 组件的情况下解决这个错误?

标签: javascriptreactjsreact-proptypes

解决方案


如果您可以声明 a是可以在 rendernode中使用的任何内容,那么它会起作用:

// 可以呈现的任何内容:数字、字符串、元素或数组 //(或片段)包含这些类型:

可选节点:PropTypes.node,

CheckboxInput.propTypes = {
  label: PropTypes.node,
  classNames: PropTypes.string
};

推荐阅读