简体   繁体   English

React - 无法从子道具中获取功能

[英]React - Can't get function to fire from child props

I am trying to get this function to fire from on click call in a child component. 我试图从子组件中的单击调用启动此功能。

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
  });
  };
}

This on click is being fired from within a Cart component 单击此按钮将从Cart组件中触发

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

The cart component is being added to the ItemDetails component here 购物车组件正在此处添加到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>
    )
 }
}

Finally the ItemDetails component is added into the app.js like so 最后,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>
);
};

If I remove the () = > before the this.getTotalOfItems() it fires the function on the onClick, however it causes an infinite loop of re-rendering out the app causing an error. 如果我在this.getTotalOfItems()之前删除了()=>,它会触发onClick上的函数,但是它会导致无限循环重新渲染应用程序而导致错误。

Is there anyway to fix this? 有没有什么办法解决这一问题? I am a novice at React and this is one of my first projects using it. 我是React的新手,这是我使用它的第一个项目之一。 Any advice shall be appreciated. 任何建议将不胜感激。

Sorry if this isn't explained to well, I am happy to provide any additional information if required. 很抱歉,如果没有得到解释,我很乐意在必要时提供任何其他信息。

Thanks! 谢谢!

You have to trigger getPrice method, now all you do is binding this context. 你必须触发getPrice方法,现在你要做的就是绑定this上下文。 Instead of props.getPrice.bind(this) you should have: props.getPrice() 而不是props.getPrice.bind(this)你应该有: props.getPrice()

props.getPrice.bind(this) doesn't call the function it just binds 'this' to it. props.getPrice.bind(this)不调用它只是将'this'绑定到它的函数。

You should use props.getPrice() instead, also you don't have to bind the context of a children to it. 您应该使用props.getPrice() ,也不props.getPrice()子项的上下文绑定到它。

Some additionnal tips/explanations : 一些额外的提示/解释

You can rewrite all your functions calls like this one : 您可以像这样重写所有函数调用:

getPrice={ () => this.getTotalOfItems() }

to

getPrice={this.getTotalOfItems}

It will pass the function to the child instead of creating a function which trigger the function (same result, better performance) 它会将函数传递给子而不是创建一个触发函数的函数(结果相同,性能更好)

But if you do this : 但是如果你这样做

getPrice={this.getTotalOfItems()}

It'll trigger the function at each render() , causing an infinite loop if the function triggers a render() itself by calling this.setState() 它将在每个render()处触发函数,如果函数通过调用this.setState()触发render()本身, this.setState()导致无限循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM