【发布时间】:2018-08-16 11:17:09
【问题描述】:
我正在尝试在 React JS 前端实现个人资料图片选项,类似于 Google Plus/Gmail 所做的。如果没有可用的头像,则提取并显示名称中单词的首字母,而不是头像。
我已经制作了适当的 div 和 CSS 用于显示,首字母也被提取出来但没有显示。 This image is a good example.
HTML:
<li className="nav-item">
<div id="container_acronym">
<div id="name_acronym">
{this.acronym_name(this.state.lead_details.customer_name)}
</div>
</div>
</li>
CSS:
#container_acronym {
width: 90px;
height: 90px;
border-radius: 100px;
background: #333;
}
#name_acronym {
width: 100%;
text-align: center;
color: white;
font-size: 36px;
line-height: 100px;
}
JavaScript:
acronym_name(str){
var regular_ex=/\b(\w)/g;
var matches = str.match(regular_ex);
var acronym = matches.join('');
document.getElementById("name_acronym").innerHTML = acronym;
}
【问题讨论】:
-
另外我收到“无法读取未定义的属性‘匹配’”错误。
-
您的
this.state.lead_details.customer_name必须是undefined才能发生这种情况。 Check out conditional rendering -
正确。它在中未定义,因为我通过在其中添加 comsole.log() 发现了这一点。我不明白为什么会这样。只有在从数据源中成功检索到lead_details 时,才应该渲染该部分。在此代码块外检索。我尝试将上面的 HTML 替换为 console.log(this.state.lead_details.customer_name) 并在控制台中呈现名称。
标签: javascript html reactjs web frontend