简体   繁体   中英

React passing value from child to another parent

I have a problem passing value from component named Item to component NavBar . The tree looks like this.

树

In Item component I have button, that is calling function handleAddToCart

<button onClick={this.handleAddToCart} style={btnStyle} className="btn btn-secondary btn-sm">ADD TO CART</button>


handleAddToCart = () => {
    console.log(this.state.price, this);
    this.props.changeValue(this.state.price)
};

And in NavBar component I have a function that is supposed to receive price of item

changeValue = (totalPrice) => {
    this.setState({
        totalPrice: totalPrice
    });
};

And then display it

{this.state.totalPrice.toFixed(2)}

the problem is that in Item component function called changeValue is unrecognized. Is it even possible to pass values straight to another child without passing it step by step to parent=>another parent=>child ? How should it be done correctly?

Figured it out. Button in item component:

onClick={() => this.props.handler(this.state.price)}

Passing values to item in itemsList

{this.props.items.map(item => <Item
                key={item.id}
                price={item.price}
                img={item.img}
                imgDesc={item.imgDesc}
                itemDesc={item.itemDesc}
                handler={this.props.handlePriceChange}
            />)}

In App component function:

handlePriceChange = (priceValue) => {
    this.setState({totalPrice: this.state.totalPrice + priceValue});
    this.setState({totalItems: this.state.totalItems + 1});
};

and passing function to child (itemsList)

<ItemsList items={this.state.items} handlePriceChange={this.handlePriceChange}/>

Finally in navBar:

Items: {this.props.totalItems}
Sum: {this.props.totalPrice.toFixed(2)}

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