我是新来的人。
我有这样的输入文字
<input type="text" class="form-control" placeholder="Number Only"
value={that.state.value}
ref={"qtype3" + item.questionId}
/>
现在在一种方法中,我想获取在文本框中输入的值,所以我在该方法中编写了以下代码块:
const uniqueNames = Array.from(new Set(this.state.arrrefs));
if (uniqueNames.length > 0) {
for (let i = 0; i < uniqueNames.length; i++) {
var inval = uniqueNames[i];
var ans = this.refs.inval.value;
var newans = {
taskId: this.props.location.state.tskId,
userId: this.props.location.state.userid,
questionId: "",
answer: ans
};
this.state.radioObj.push(newans);
}
}
这里,arrrefs是状态为带有多个文本框的引用的数组。在变量inval
中,我得到了arrrefs的第一个值。但我在var ans = this.refs.inval.value;
TypeError:无法读取未定义的属性“值”
如果我在this.refs.inval.value
行而不是inval
中传递硬编码值,则会得到响应。
例如,我的uniqueNames = [“ qtype3800316”,“ qtype3800317”,“ qtype3800318”,“ qtype3800324”]
所以我想要this.refs.qtype3800316.value
我在这里做什么错了?
答案 0 :(得分:1)
如果要通过变量访问数组/对象,请尝试使用[]
运算符。
this.refs[inval].value
答案 1 :(得分:0)
尝试使用: this.refs.inval
您还可以console.log(this.refs)并检查其中的内容。