javascript - Reactjs 在其他组件中传递一个组件
问题描述
我正在尝试将自定义组件传递给另一个组件,父组件应该像包装器一样工作,将自定义组件放在最后的特殊部分,但我遇到了这个错误Uncaught Error: Objects are not valid as a React孩子(找到:带有键 {...} 的对象)。如果您打算渲染一组子项,请改用数组。我读了很多帖子,但这些解决方案不起作用,这是最相似的问题,但对我不起作用。
包装器
function Wrapper(props: Props) {
const { title, icon, content } = props
return (
<div className={ Styles.wrapperContainer }>
<h1>{ title }</h1>
{
icon &&
<img src={`/assets/images/${icon || 'notification-bell-icon.svg'}`} alt="" />
}
{ content } // <-
</div>
)
}
调用 Wrapper 组件
<Wrapper
title="My tittle"
content={<Button text="press me" type={ButtonTypes.DEFAULT} />}
/>
按钮组件
function Button(props: Props){
const { type, text, icon } = props
return (
<span className={`${Styles.buttonContainer} ${Styles[type]}`}>
{
type === ButtonTypes.ICON_BUTTON ?
<img src={`/assets/images/${icon}`} alt=""/> :
(
icon ?
<><LineIcon icon={icon}/>{ text }</> :
{ text }
)
}
</span>
)
}
解决方案
好的,感谢您的帮助,我发现<Button />
组件有问题,我像这样更改了它,它也可以<></>
在作品上添加标签{ text }
。
谢谢
function Button(props: Props){
const { type, text, icon } = props
return (
<span className={`${Styles.buttonContainer} ${Styles[type]}`}>
{
type === ButtonTypes.ICON_BUTTON ?
<img src={`/assets/images/${icon}`} alt=""/> :
(
<>
{ icon && <LineIcon icon={icon}/> }
{ text }
</>
)
}
</span>
)
}
推荐阅读
- c++-cli - 接受 C++/CLI 中带有和不带有“hat”运算符的托管结构。有什么不同?
- sharepoint - 计算两个日期之间的差异以计算小时和分钟
- haskell - 为什么这个应用实例是非法的?
- nativescript - Nativescript:在哪里存储导航?
- java - n 位二进制置换表示的时间复杂度
- c++ - 这是未初始化的变量使用未定义的行为吗
- html - 关闭代码后html链接仍然装箱
- python - 什么是可导航字符串 (HTML)?
- angular - ChartJs 不能在没有错误的角度 4 中工作
- java - spring webclient 和 httpsurlconnection 请求 https 接口的一些区别