React Accessing a value from an array

2020-05-02 10:24发布

问题:

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...

I have tried the following

console.log(this.state.telephone.name)

and...

console.log(this.state.telephone.tidx.name)

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>
     ))}

Any advice greatly appreciated as I am fairly new to forms in React. Thanks.

回答1:

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>
 ))}