我最近一直在努力学习React,尽管最近缺乏Javascript经验,而且我遇到了一些意想不到的障碍。我正在重写我的个人网站(基本上是静态HTML,后端有一些PHP),我要做的一件事就是从外部JSON文件中加载我的简历的详细信息(下一步是从一个静态JSON文件,用于调用将返回数据的端点。
在我的简历中,我列出了几个工作的成就列表,其中一些我希望返回少量标记(在一个案例中,我是发明人的专利链接)另一个只是将一个句子应用于单个句子,以引起对一些无偿工作的关注)。我知道我可以使用React中的dangerouslySetInnerHTML()方法传入包含标记的String并让它呈现......我似乎无法让它工作。
以下是相关组件:
import React, {Component} from 'react';
class WorkEntry extends Component {
constructor(props) {
super(props);
var _this = this;
this.usedSkillsTags = [];
this.responsibilitiesTags = [];
this.achievementsTags = [];
this.props.technologiesUsed.forEach(function (item) {
_this.usedSkillsTags.push(<li>{item}</li>)
});
this.props.responsibilities.forEach(function (item) {
_this.responsibilitiesTags.push(<li>{item}</li>)
});
this.props.achievements.forEach(function (item) {
if(item.indexOf("<") > -1 && item != null ) {
_this.achievementsTags.push(<li dangerouslySetInnerHTML={ { _html : item.toString() } }/>)
}
else{
_this.achievementsTags.push(<li>{item}</li>)
}
});
}
render() {
return (
<div>
<div class="row">
<div class="well">
<div class="row">
<div class="col-sm-12">
<h3>{this.props.companyName} -
<small> {this.props.jobTitle}</small>
</h3>
</div>
</div>
<div class="row">
<div class="col-sm-12">{this.props.startDate} - {this.props.endDate}</div>
</div>
<div class="row">
<div class="col-sm-4">
<h4 class="text-center">Skills Used</h4>
<ul class="wrapped-list">
{this.usedSkillsTags}
</ul>
</div>
<div class="col-sm-8">
<h4 class="text-center">Responsibilities</h4>
<ul>
{this.responsibilitiesTags}
</ul>
</div>
</div>
{ this.achievementsTags.length > 0 &&
<div class="row">
<div class="col-sm-12">
<h4 class="text-center">Notable Projects and Achievements</h4>
<ul>
{this.achievementsTags}
</ul>
</div>
</div>
}
</div>
</div>
</div>
);
}
}
export default WorkEntry;
这是导致问题的Json:
{
"companyName": "Eloquence Communications",
"jobTitle": "Lead Developer",
"startDate": "January 2013",
"endDate": "February 2014",
"technologiesUsed": [
"Java",
"SQL",
"Idea",
"Bamboo",
"Nexus",
"Maven",
"Git",
"JavaFX",
"Python"
],
"responsibilities": [
"Designed overall architecture for hospital Nurse Call System",
"Managed complex build process for multiple Java applications using Git, Maven, Nexus, and Bamboo",
"Proposed idea which was eventually patented by employer",
"Lead a small team of developers to convert an idea into a product"
],
"achievements": [
"After proposing a method of nursing staff tracking and authentication using NFC, was named as an inventor on <a href='http://patents.justia.com/patent/20140330575'>patent application #20140330575</a>"
]
}
我显然已经阅读了错误消息中的链接,但我发现文档中的代码与我自己的代码没有区别。任何人都可以在这里提供一些专业知识吗?
答案 0 :(得分:3)
dangerouslySetInnerHTML
需要__html
(请注意两个下划线),而不是_html
将其更改为
dangerouslySetInnerHTML={ { __html : item.toString() } }