首页 > 解决方案 > Reactjs 在其他组件中传递一个组件

问题描述

我正在尝试将自定义组件传递给另一个组件,父组件应该像包装器一样工作,将自定义组件放在最后的特殊部分,但我遇到了这个错误Uncaught Error: Objects are not valid as a React孩子(找到:带有键 {...} 的对象)。如果您打算渲染一组子项,请改用数组。我读了很多帖子,但这些解决方案不起作用,这是最相似的问题,但对我不起作用。

将图标组件传递给 ReactJS 中的另一个组件

包装器

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>
    )
}

标签: javascriptreactjstypescript

解决方案


好的,感谢您的帮助,我发现<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>
    )
}

推荐阅读