简体   繁体   中英

How to setState of an object inside an array in parent component from child component?

I want to change the value of an object inside an array, which is inside my state, which is inside my parent component, from my child component. The problem is I need both the event.target.value and the item.id (which is a uuid) so I can know which object to change. However, after all my attempts, I've only been able to pass one value, either the input value or the item.id. Any help is appreciated.

Here is my input component:

<Input onChange={this.props.updateQuantity} defaultValue={item.unit_quantity || ""}/>

and here is updateQuantity:


    updateQuantity = (e,id) => {
        var copy = [...this.state.items]
        for(let i = 0; i<copy.length; i++){
            if(copy[i].id == id){
                copy[i].unit_quantity = e.target.value;
                break;
            }
        }
        this.setState({
            items: copy
        })

    }

You can use the ES6 arrow function and pass the additional arg. (event) though that.

<Input onChange={(event)=>this.props.updateQuantity(event,item.id)} defaultValue={item.unit_quantity || ""}/>

and in the parent component use as it is:

updateQuantity = (event,id) => {
    console.log(event, id)
    // Rest of the code...
}

The child which renders the input could have an intermediate function that serves to call the updateQuantity function from the props with the right parameters.

So you change the function passed to the input onChange to a local function in the child:

<Input onChange={this.updateQuantity} defaultValue={item.unit_quantity || ""}/>

Then you create the function within the child like so:

updateQuantity = (e) => {
    this.props.updateQuantity(e, this.props.id);
}

This will call the parents function with whatever parameters you want. I'm assuming your child has its id stored within a prop but you can change it to wherever it's stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM