javascript - 是否可以将组件作为字符串道具传递?(使用组件库)
问题描述
我正在使用我的雇主提供的“可重用组件库”来呈现复选框。复选框组件的代码是:
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 组件的情况下解决这个错误?
解决方案
如果您可以声明 a是可以在 rendernode
中使用的任何内容,那么它会起作用:
// 可以呈现的任何内容:数字、字符串、元素或数组 //(或片段)包含这些类型:
可选节点:PropTypes.node,
CheckboxInput.propTypes = {
label: PropTypes.node,
classNames: PropTypes.string
};
推荐阅读
- c++ - 有没有办法在 C++ 中定义一个类时“注册”一个类?
- javascript - 在 javascript 中搜索字符串时跳过或忽略部分字符串
- azure - 通过策略启用 Azure NSG FlowLogs
- c++ - 尝试完美的正方形你能给点小费吗
- python - 在没有循环的情况下逐节填充数据框
- java - Java EE 7 批处理 API (JSR-352):可以停止单个步骤而不是所有工作吗?
- node.js - Docker usb 热插拔
- javascript - 带有 CSFR 令牌的 Axios POST 请求被拒绝 - 401
- flutter - 错误只能在初始化器中访问静态成员
- sql - 如何将 rusqlite 的 Row::get 方法用于编译时我不知道的类型?