React从数组访问值 [英] React Accessing a value from an array
问题描述
我在React中有一个表单,可以动态添加新的输入元素.这似乎正常,但我似乎无法访问此屏幕截图中所示的输入值...
I have a form in React which dynamically adds new input elements. This seems to be working ok but I cant seem to access the input values as shown in this screenshot...
我尝试了以下
console.log(this.state.telephone.name)
console.log(this.state.telephone.name)
和...
console.log(this.state.telephone.tidx.name)
console.log(this.state.telephone.tidx.name)
其中tidx是唯一键.
where tidx is the unique key.
这里是构造函数...
Here is the constructor...
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表单的新手. 谢谢.
Any advice greatly appreciated as I am fairly new to forms in React. Thanks.
推荐答案
telephone
是一个数组,因此您应该使用索引符号.
telephone
is an array, so you should be using index notation.
console.log(this.state.telephone[tidx].name)
为每个电话呈现相应的电话类型:
To render a corresponding phone-type for each telephone:
{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从数组访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!