[英]React passing value from child to another parent
I have a problem passing value from component named Item
to component NavBar
. 我将值从名为Item
的组件传递到组件NavBar
遇到问题。 The tree looks like this. 这棵树看起来像这样。
In Item
component I have button, that is calling function handleAddToCart
在Item
组件中,我有一个按钮,即正在调用功能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 在NavBar
组件中,我有一个应该接收商品价格的函数
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. 问题是在Item
组件中,名为changeValue
函数无法识别。 Is it even possible to pass values straight to another child without passing it step by step to parent=>another parent=>child ? 甚至可以直接将值直接传递给另一个孩子,而无需将其逐步传递给parent =>另一个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 将值传递给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: 在App组件功能中:
handlePriceChange = (priceValue) => {
this.setState({totalPrice: this.state.totalPrice + priceValue});
this.setState({totalItems: this.state.totalItems + 1});
};
and passing function to child (itemsList) 并将函数传递给子项(itemsList)
<ItemsList items={this.state.items} handlePriceChange={this.handlePriceChange}/>
Finally in navBar: 最后在navBar中:
Items: {this.props.totalItems}
Sum: {this.props.totalPrice.toFixed(2)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.