React从数组访问值
我在React中有一个表单,可以动态添加新的输入元素。这似乎
工作正常,但我似乎无法访问此
屏幕截图中所示的输入值…
console.log数组
我尝试了以下
console.log(this.state.telephone.name)
和…
console.log(this.state.telephone.tidx.name)
其中tidx是唯一键。
这是构造函数…
constructor() { super();
this.state = {
role: "Installer",
name: "",
telephoneType: [{ name: "" }],
telephone: [{ name: "" }],
tidx: "",
emailType: [{ email: "" }],
email: [{ email: "" }],
eidx: "",
notes: ""
};
}
and this is my function to handle the input forms…
handleTelephoneChange = tidx => evt => { const newTelephone = this.state.telephone.map((telephone, tsidx) => {
if (tidx !== tsidx) return telephone;
return { ...telephone, name: evt.target.value };
});
this.setState({ telephone: newTelephone }, () => {
// get state on callback
console.log(this.state)
console.log(this.state.telephone.name)
console.log(this.state.telephone.tidx.name)
}
);
};
and rendered like this…
{this.state.telephone.map((telephone, tidx) => (<MDBRow key={tidx} className="grey-text flex-nowrap align-items-center no-gutters my-2">
<MDBCol md="12">
<input value={telephone.name} onChange={this.handleTelephoneChange(tidx)}placeholder={`Telephone No. #${tidx + 1}`} className="form-control"/>
</MDBCol>
</MDBRow>
))}
任何建议都将不胜感激,因为我是React表单的新手。谢谢。
回答:
telephone
是一个数组,因此您应该使用索引符号。
console.log(this.state.telephone[tidx].name)
为每个电话呈现相应的电话类型:
{this.state.telephone.map((telephone, tidx) => ( <MDBRow key={tidx} className="grey-text flex-nowrap align-items-center no-gutters my-2">
<MDBCol md="12">
<input value={this.state.telephoneType[tidx].yourValue} onChange={this.defineYourTelephoneTypeEventHandler(tidx)}/>
<input value={telephone.name} onChange={this.handleTelephoneChange(tidx)}placeholder={`Telephone No. #${tidx + 1}`} className="form-control"/>
</MDBCol>
</MDBRow>
))}
以上是 React从数组访问值 的全部内容, 来源链接: utcz.com/qa/399615.html