我正在为我的投资组合网站建立一个反应应用程序。目前我有用JSX编写的应用程序,所以我可以添加如下内容:
class Project extends React.Component {
render() {
return (
<div className={this.props.project.class}>
<h1>{this.props.project.header}</h1>
<div>
<div className='description'>
<p>{this.props.project.description}</p>
<p>The Tech Stack</p>
<ul>
{
this.props.project.items.map(function(listValue){
return <li>{listValue}</li>;
})}
</ul>
</div>
<div className='image'>
</div>
</div>
</div>
);
}
}
到我的组件。我目前正在另一个名为Text.js的文件中管理我的长文本字符串:
export let exampleText = "Graded is a application developed by <a href='google.com'> Link here. </a> and myself for our second year user interfaces course.";
在我的jsx文件中访问它:
var gradedItems = {
class: "gradedSection content",
header: "Graded",
description: Text.exampleText,
items : ["Java", "Android"]
}
然后它会显示在上面组件的<p>
标记中。但是,正如我所提到的,链接实际上并没有渲染,并且html标记没有被渲染。所以它看起来像一些文本,然后在网站上的标签。
我应该如何在此字符串中添加这些html标记,以便在组件呈现时,内部的html元素会被渲染出来?
在这种情况下是否有可能实现我正在努力实现的目标?
一如既往地谢谢你!
答案 0 :(得分:3)
您只需使用dangerouslySetInnerHTML即可。
使用示例:
let exampleText = "Graded is a application developed by <a href='google.com'> Link here. </a> and myself for our second year user interfaces course.";
function Component() {
return <div dangerouslySetInnerHTML={{__html: exampleText }} />;
}
答案 1 :(得分:2)
首先 npm安装html-react-parser
import Parser from 'html-react-parser';
var exampleText = 'Graded is a application developed by <a href='google.com'> Link here. </a> and myself for our second year user interfaces course.';
render: function() {
return (
<div>{Parser(exampleText)}</div>
);
}
答案 2 :(得分:1)
一个选项是将Text.js
中的字符串更改为html位,例如
export const exampleText = (
<span>
Graded is a application developed by
<a href='google.com'> Link here. </a>
and myself for our second year user interfaces course.
</span>
);