簡體   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