连接字符串和 <a href=""></a>

hel*_*pie 1 javascript string string-concatenation reactjs

我正在使用 ReactJS,我想要一个字符串,然后是一个链接,如下所示

const example = "Hello I'm a string" + <a href="/link">And this is a link</a>
Run Code Online (Sandbox Code Playgroud)

目前我不断得到 Hello I'm a string [object Object]

如何让文本和链接正确连接?

T.J*_*der 5

如果您真的需要这样做,您可以使用React Fragment(或任何包装元素,如 a span),如下所示:

const example = <>Hello I'm a string<a href="/link">And this is a link</a></>;
Run Code Online (Sandbox Code Playgroud)

或者使用更旧的更详细的语法:

const example = <React.Fragment>Hello I'm a string<a href="/link">And this is a link</a></React.Fragment>;
Run Code Online (Sandbox Code Playgroud)

稍后您想在另一个组件中使用它时,您将使用 JSX 表达式,例如:

return <div>{example}</div>;
Run Code Online (Sandbox Code Playgroud)

现场示例:

const example = <>Hello I'm a string<a href="/link">And this is a link</a></>;
Run Code Online (Sandbox Code Playgroud)
const example = <React.Fragment>Hello I'm a string<a href="/link">And this is a link</a></React.Fragment>;
Run Code Online (Sandbox Code Playgroud)

但通常没有必要,您在构建渲染树时进行组合(类组件的render方法返回值,或功能组件的返回值)。例如:

function Example() {
    const msg = "Hello I'm a string";
    const link = <a href="/link">And this is a link</a>;

    // Composing them
    return <div>{msg}{link}</div>;
}
Run Code Online (Sandbox Code Playgroud)

现场示例:

return <div>{example}</div>;
Run Code Online (Sandbox Code Playgroud)
// The Stack Snippets version of Babel is too old
// for <>...</> syntax.
function Example() {
    const example = <React.Fragment>Hello I'm a string<a href="/link">And this is a link</a></React.Fragment>;

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

ReactDOM.render(<Example/>, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)