You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Fragment内嵌Link元素显示为[object Object]问题求助

React Fragment内嵌Link显示异常的解决方法

问题描述

使用React Fragment时,文本中内嵌的Link元素被渲染为[object Object],显示效果如下:

You must first verify your email address before logging in. Would you like to [object Object] the email confirmation link?

相关精简代码:

export default function MyComponent() {
    let loginError: JSX.Element = <>You must first verify your email address before logging in. Would you like to ${<Link to="../account/resend-email-confirmation" className="alert-link">resend</Link>} the email confirmation link?</>;

    return (
        <div>
            {loginError}
        </div>
    )
}

问题原因

你将<Link>组件放入了模板字符串的${}语法中,JSX元素在模板字符串中会被自动调用toString()方法,而React组件对象转字符串的结果就是[object Object],导致显示异常。

修复方案

直接在Fragment中将文本与<Link>组件作为并列的子元素,不要用模板字符串包裹整段内容:

export default function MyComponent() {
    let loginError: JSX.Element = (
        <>
            You must first verify your email address before logging in. Would you like to{" "}
            <Link to="../account/resend-email-confirmation" className="alert-link">
                resend
            </Link>{" "}
            the email confirmation link?
        </>
    );

    return <div>{loginError}</div>;
}

补充说明

如果需要动态组合多个内容片段,也可以使用数组(需为每个元素添加唯一key):

export default function MyComponent() {
    let loginError: JSX.Element = (
        <>
            {[
                "You must first verify your email address before logging in. Would you like to ",
                <Link key="resend-link" to="../account/resend-email-confirmation" className="alert-link">resend</Link>,
                " the email confirmation link?"
            ]}
        </>
    );

    return <div>{loginError}</div>;
}

内容的提问来源于stack exchange,提问作者PixelPaul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:12:46