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

问题描述 投票:0回答:2

我想从我的子组件中更改数组内部对象的值,该数组位于我的父组件内部。问题是我需要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
        })

    }
javascript reactjs antd
2个回答
1
投票

您可以使用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...
}

-1
投票

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

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.