我试图在React JS前端显示一些文本代替配置文件图像,当它不可用时。基本上,我将当前客户名称传递给一个函数,该函数提取所有单词的第一个字符。名字。我只能显示名称但是当我进行功能调用时,我看不到属性'匹配'未定义"错误,页面不呈现。 Console.log()显示未定义。
HTML:
var $theTarget;
$("input[id^='field'][id$='A']").on('click', function() {
$theTarget = $(this);
$("#bg").fadeIn(400, function() {
$("#modal").fadeIn(400);
});
});
$("input[id^='field'][id$='B']").on('click', function() {
$theTarget = $(this);
$("#bgB").fadeIn(400, function() {
$("#modalB").fadeIn(400);
});
});
$("#modal img").on('click', function() {
var text = $(this).siblings('.descr').text();
$("#modal").fadeOut(400, function() {
$("#bg").fadeOut(400, function() {
$theTarget.val(text);
});
});
});
$("#modalB img").on('click', function() {
var text = $(this).siblings('.descr').text();
$("#modalB").fadeOut(400, function() {
$("#bgB").fadeOut(400, function() {
$theTarget.val(text);
});
});
});
JS:
.field {
margin: 10px;
}
#bg {
position: fixed;
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.5);
left: 0;
top: 0;
display: none;
}
#modal {
position: absolute;
height: 300px;
width: 600px;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -300px;
background: #fff;
display: none;
}
#modal div {
display: inline-block;
}
#modal img {
height;
180px;
width: 180px;
opacity: 0.8;
cursor: pointer;
}
#modal img:hover {
opacity: 1;
}
#bgB {
position: fixed;
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.5);
left: 0;
top: 0;
display: none;
}
#modalB {
position: absolute;
height: 300px;
width: 600px;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -300px;
background: #fff;
display: none;
}
#modalB div {
display: inline-block;
}
#modalB img {
height;
180px;
width: 180px;
opacity: 0.8;
cursor: pointer;
}
#modalB img:hover {
opacity: 1;
}
.descr {
position: relative;
width: 180px;
padding: 0 0 0 70px;
}
答案 0 :(得分:1)
this.state.lead_details.customer_name
似乎未定义,所以你需要抓住那个案例。
你有多种方法可以做到这一点,如果你使用babel这个声明应该有默认值:
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;
}
否则,如果给出了undefined,你也可以检查函数内部:
acronym_name(str){
if (typeof str == 'undefined') {
str = '';
}
var regular_ex=/\b(\w)/g;
var matches = str.match(regular_ex);
var acronym = matches.join('');
document.getElementById("name_acronym").innerHTML = acronym;
}
最后,你可以在某种程度上防止首先给函数提供undefined。例如:
<li className="nav-item">
<div id="container_acronym">
<div id="name_acronym">
{this.acronym_name(this.state.lead_details.customer_name || '')}
</div>
</div>
</li>
答案 1 :(得分:1)
acronym_name(str){
if (typeof str == 'undefined') {
str = '';
}
else{
var regular_ex=/\b(\w)/g;
var matches = str.match(regular_ex);
var acronym = matches.join('');
return acronym;
}
}