【问题标题】:React passing value from child to another parent反应将值从孩子传递给另一个父母
【发布时间】:2019-01-01 14:01:43
【问题描述】:

我在将值从名为 Item 的组件传递到组件 NavBar 时遇到问题。这棵树看起来像这样。

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

NavBar 组件中,我有一个应该接收商品价格的函数

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

然后显示出来

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

问题是在Item 中调用changeValue 的组件函数无法识别。甚至可以将值直接传递给另一个孩子,而无需将其逐步传递给 parent=>another parent=>child 吗?应该怎么做才正确?

【问题讨论】:

  • 另外一种方法是使用 Redux,然后你就不需要通过 parent
  • 可能没有正确实现,我通常认为它是一棵树,因为我还没有使用 Redux,共享状态应该在树的顶部。所以父母双方的父母都应该有状态。更新该单一状态应该在任何地方更新它。
  • 如果您不想使用 Redux 或在某些父组件中创建共享状态,请查看此 reactjs.org/docs/lifting-state-up.html
  • 哪个属性从父组件传递到子组件?!你应该把它作为道具传递。我看不到那个。请解释一下。
  • 我最终将值从 App 传递到 NavBar,默认情况下为 0,但现在我坚持从 Item 组件传递价格并在 App 组件中更新它。我试图从 Item 组件调用 App 组件中的函数来更新它,但它没有看到声明的父函数。

标签: javascript reactjs single-page-application


【解决方案1】:

想通了。 项目组件中的按钮:

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

将值传递给 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}
            />)}

在App组件函数中:

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

并将函数传递给子项(itemsList)

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

终于在导航栏中:

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

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2018-03-29
    • 2018-02-07
    • 2020-09-19
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多