【问题标题】:Displaying name initials instead of profile picture显示姓名缩写而不是个人资料图片
【发布时间】: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


【解决方案1】:

您需要从acronym_name(str) 函数返回名称,而不是设置innerHTML,例如:

...
acronym_name(str){
    var regular_ex=/\b(\w)/g;
    var matches = str.match(regular_ex);
    var acronym = matches.join('');
    //return the acronym
    return acronym;
}

【讨论】:

  • 当我调试我的代码时,innerHTMLreturn acronym 都做了同样的事情。我在上面的 cmets 中添加了工作代码的链接。
猜你喜欢
相关资源
最近更新 更多
热门标签