繁体   English   中英

如何在子组件的父组件中的数组内设置对象的状态?

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

我想从我的子组件中更改数组内部对象的值,该数组位于我的父组件内部。 问题是我需要event.target.value和item.id(这是一个uuid),所以我可以知道要更改的对象。 但是,经过我所有的尝试,我只能传递一个值,输入值或item.id. 任何帮助表示赞赏。

这是我的输入组件:

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

这里是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
        })

    }

您可以使用ES6箭头功能并传递其他arg。 (事件)尽管如此。

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

并在父组件中使用原样:

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

呈现输入的子updateQuantity可以具有中间函数,该函数用于使用具有正确参数的props调用updateQuantity函数。

因此,您将传递给输入onChange的函数更改为子项中的本地函数:

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

然后在子项中创建函数,如下所示:

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

这将使用您想要的任何参数调用parent函数。 我假设您的孩子的id存储在道具中,但您可以将其更改为存储的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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