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

Concatenate a String and <a href=""></a>

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

const example = "Hello I'm a string" + <a href="/link">And this is a link</a>

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

如何正确连接文本和 link?

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

const example = <>Hello I'm a string<a href="/link">And this is a link</a></>;

或使用较旧的更冗长的语法:

const example = <React.Fragment>Hello I'm a string<a href="/link">And this is a link</a></React.Fragment>;

稍后你想在另一个组件中使用它,你可以使用 JSX 表达式,例如:

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

实例:

// 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"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

但通常没有必要,您在构建渲染树时组合了一些东西(class 组件的 render 方法 return 值,或功能组件的 return 值).例如:

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

实例:

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

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

您应该将变量视为 React 组件(参见其他答案)或字符串:

const example2 = "Hello I'm a string" + '<a href="/link">And this is a link</a>'

为了您的工作方法,您需要允许您的 HTML 模板注入真实代码,在本例中为 <a></a> 标记。这是一种有点危险的方法,因为您同时打开您的网站以进行攻击,因为有人可能会注入实际上 运行 在您的服务器上的代码。

虽然我这么说,但我对 React 还不够熟悉,不知道是否有一种方法可以安全地注入代码而不会受到潜在的攻击。

我建议您分解字符串,而不是连接 link,将您的 HTML 模板更新为如下所示:<p>{{helloString}} <a href="{{linkHref}}">{{linkString}}</a>.

您也可以完全在 JS 中创建元素并将其附加到您想要的 div 中:请参阅 W3C 说明以了解如何实现 https://www.w3schools.com/JSREF/met_document_createelement.asp