【发布时间】:2017-12-11 17:08:29
【问题描述】:
我的例子是一个简单的订单。
我有一个主组件 (Order),在这个组件内我呈现子组件的动态列表 (OrderLine)
class Order extends React.Component {
...
render() {
return <div>
<strong>Total: $ {this.getTotal()}</strong>
<table id='orderlines' style={tableStyles}>
<tbody>
{this.getLines()}
</tbody>
</table>
</div>
}
getLines = () => {
return this.state.orderLines.map((item, _) =>
<OrderLine key={item.id} {...item} />)
}
}
子组件 (OrderLine) 具有输入 (quantity) 和方法 getTotal(),用于计算该行的总和
getTotal = () => (this.props.product.price * this.state.quantity).toFixed(2);
目标是计算订单的总和。
我想做类似sum(map(allOrderLines, (line) => line.getTotal())) 的操作,但我无法从Order 组件访问orderLine.getTotal()。
那么,最好的方法是什么?我知道如何从孩子更新父母的状态(将回调函数作为道具),但是可以从父母那里做到吗?
此处为完整示例:
【问题讨论】:
标签: javascript reactjs