gpt4 book ai didi

javascript - React - 无法从子 Prop 中获取功能

转载 作者:行者123 更新时间:2023-11-29 15:13:29 24 4
gpt4 key购买 nike

我试图让这个函数在子组件中的点击调用中触发。

getTotalOfItems = () => {

console.log('anything at all?')
if (this.props.cart === undefined || this.props.cart.length == 0) {
return 0
} else {

const items = this.props.cart
var totalPrice = items.reduce(function (accumulator, item) {
return accumulator + item.price;
}, 0);

this.setState({
estimatedTotal: totalPrice
});
};
}

这个点击是从购物车组件中触发的

<button onClick={() => {props.addToCart(item); props.getPrice.bind(this)} }>+</button>

正在将购物车组件添加到此处的 ItemDetails 组件

export default class ItemDetails extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
render() {
return(
<div>
<Button
className="item-details-button"
bsStyle="link"
onClick={() => this.setState({open: !this.state.open})}
>
{this.state.open === false ? `See` : `Hide`} item details
{this.state.open === false ? ` +` : ` -`}
</Button>
<Collapse in={this.state.open}>
<Cart
getPrice={this.props.getPrice}
/>
</Collapse>
</div>
)
}
}

最后像这样将 ItemDetails 组件添加到 app.js 中

 render() {
return (
<div className="container">
<Col md={9} className="items">
<ProductListing products={this.props.initialitems} />
</Col>
<Col md={3} className="purchase-card">
<SubTotal price={this.state.total.toFixed(2)} />
<hr />
<EstimatedTotal
price={this.state.estimatedTotal.toFixed(2)} />
<ItemDetails
price={this.state.estimatedTotal.toFixed(2)}
getPrice={ () => this.getTotalOfItems() }
/>
<hr />
<PromoCodeDiscount
giveDiscount={ () => this.giveDiscountHandler() }
isDisabled={this.state.disablePromoButton}
/>
</Col>
</div>
);
};

如果我在 this.getTotalOfItems() 之前删除 () => 它会触发 onClick 上的函数,但是它会导致重新呈现应用程序的无限循环,从而导致错误。

有办法解决这个问题吗?我是 React 的新手,这是我使用它的第一个项目。任何建议将不胜感激。

很抱歉,如果这没有解释清楚,我很乐意在需要时提供任何其他信息。

谢谢!

最佳答案

您必须触发getPrice 方法,现在您要做的就是绑定(bind)this 上下文。而不是 props.getPrice.bind(this) 你应该有: props.getPrice()

关于javascript - React - 无法从子 Prop 中获取功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52040932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com