使用需要连接的名称字符串访问React ref属性
React ref attribute access with name string that needed to be concatenated
在React/javascript中,有一个像这样的map函数
{this.state.caseDetails.plaintiff.map((p, i)=>{
return(
<div className={`col-lg-${inputWidth}`}>
<input type="hidden" ref={'plaintiff_id_' + i} value={p.id} />
<input type='text' ref={'plaintiff_name_' + i} className='form-control' defaultValue={p.name}/>
</div>
)
})}
我通过连接I变量创建了如上所述的属性plaintiff_id_0直到数组的大小。然而,现在的问题是,我想获得这些数据的值使用ref,所以我创建了一个for循环像这样:
for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {
console.log(this.refs.("plaintiff_id_".concat(i)).value);
//Tried this.refs.("plaintiff_id_"+i).value etc.
}
和不同的版本连接i到字符串,但它一直告诉我,这是一个语法错误,无论如何访问这些ref我想要的?
试试这个:
for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {
console.log(this.refs["plaintiff_id_".concat(i)].value);
//OR
console.log(this.refs["plaintiff_id_" + i].value);
}
您可以使用括号表示法,如:this.refs['plaintiff_id_' + i]
.
您应该能够使用ref访问DOM元素,如下所示:
for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {
var plaintiffIdRef = "plaintiff_id_" + i;
console.log(React.findDOMNode(this.refs[plaintiffIdRed]).value)
var plaintiffNameRef = "plaintiff_name_" + i;
console.log(React.findDOMNode(this.refs[plaintiffNameRef]).value)
}
相关文章:
- 通过[]访问的字符串的字符是字符串
- 如何从字符串变量访问对象属性
- 以数组形式访问字符串变量的Javascript
- 为什么我得到“;错误:预期"同时访问字符串
- 即使使用 angular.fromJson() 也无法从 json 对象访问字符串
- Javascript / JQuery循环访问已发布的ajax数据字符串以为其分配新值
- 若字符串为null,则通过启发式方法无法访问代码,将null赋值给变量
- ASP.NET MVC - 在客户端 JS 中访问 C# 字符串
- 直接访问字符串方法
- 访问字符串化的JSON对象
- 绑定后的访问字符串
- 如何使用字符串变量访问字符串数组?Javascript
- Javascript原型字符串-访问字符串值
- 如何使用AJAX从PHP访问字符串到jQuery
- 在jquery中访问字符串形式的值
- JSON对象中的访问字符串
- 访问字符串存储在一个ViewBag ajax成功
- foreach绑定到字符串列表时,如何访问字符串
- 循环访问字符串中的数字(仅限数字)
- 在javascript中,我可以覆盖括号来访问字符串中的字符吗