如何解决连接字符串和<a href=""> </a>
我正在使用ReactJS,我想要一个字符串,然后是如下所示的链接
const example = "Hello I'm a string" + <a href="/link">And this is a link</a>
此刻我不断收到Hello I'm a string [object Object]
如何获取文本和正确连接的链接?
解决方法
如果您确实需要这样做,可以使用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>
但是通常没有必要,您在构建渲染树时就编写了东西(类组件的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>;
}
实时示例:
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>
,
为使工作方式有效,您需要允许HTML模板注入真实的代码,在这种情况下为<a></a>
标签。这是一种危险的方法,因为您同时要开放网站进行攻击,因为有人可能注入实际上将在您的服务器上运行的代码。
尽管我这么说,但是我对React并不十分了解,是否知道是否有一种方法可以安全地注入代码而不会受到潜在的攻击。
我建议您分解字符串,而不是连接链接,而是将HTML模板更新为以下形式:<p>{{helloString}} <a href="{{linkHref}}">{{linkString}}</a>
。
您还可以在JS中完全创建元素,并将其添加到所需的div中:有关如何实现https://www.w3schools.com/JSREF/met_document_createelement.asp的信息,请参见W3C指令
,您应该将变量视为React组件(请参见其他答案)或作为字符串:
const example2 = "Hello I'm a string" + '<a href="/link">And this is a link</a>'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。