【问题标题】:React - Can't get function to fire from child propsReact - 无法从子道具触发功能
【发布时间】:2019-02-02 02:06:01
【问题描述】:

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

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 的新手,这是我第一个使用它的项目之一。任何建议将不胜感激。

很抱歉,如果没有很好地解释这一点,如果需要,我很乐意提供任何其他信息。

谢谢!

【问题讨论】:

    标签: javascript reactjs function components


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      props.getPrice.bind(this) 不会调用它只是将 'this' 绑定到它的函数。

      您应该改用props.getPrice(),而且您不必将孩子的上下文绑定到它。

      一些额外的提示/解释

      您可以像这样重写所有函数调用:

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

      getPrice={this.getTotalOfItems}
      

      它将函数传递给子函数,而不是创建触发函数的函数(结果相同,性能更好)

      但如果你这样做

      getPrice={this.getTotalOfItems()}
      

      它会在每个render()触发函数,如果函数通过调用this.setState()本身触发render(),则会导致无限循环

      【讨论】:

        猜你喜欢
        • 2019-03-21
        • 1970-01-01
        • 2021-09-06
        • 2020-03-31
        • 1970-01-01
        • 1970-01-01
        • 2013-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多