【发布时间】:2020-11-05 00:32:01
【问题描述】:
在我观看的项目中,它们使用类组件,但我想使用钩子对功能组件进行这些操作。你怎么能帮助我的家伙?我尝试了很多次,但无法进行此翻译。我还在努力
我的代码(导入的数据是“成分”):
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
ingredients: [],
totalPrice: 0
}
this.addIngredients = this.addIngredients.bind(this)
this.removeIngredients = this.removeIngredients.bind(this)
this.calculateTotal = this.calculateTotal.bind(this)
}
addIngredients(product) {
this.setState({
ingredients: [...this.state.ingredients].concat([
{ ...product, displayId: Math.random() }
])
})
}
removeIngredients(product) {
const selectedProduct = this.state.ingredients.find((ingredient) => {
return ingredient.name === product.name
})
const targetId = selectedProduct.displayId
this.setState({
ingredients: this.state.ingredients.filter((ingredient) => {
return ingredient.displayId !== targetId
})
})
}
calculateTotal() {
let total = 4
this.state.ingredients.forEach((item) => {
total += item.price
})
return total.toFixed(2)
}
render() {
return (
<div>
<Hamburger ingredients={this.state.ingredients} />
<TotalPrice total={this.calculateTotal} />
<ItemList
items={ingrediends}
addIngredients={this.addIngredients}
removeIngredients={this.removeIngredients}
selectedIngredients={this.state.ingredients}
/>
</div>
)
}
}
export default App
【问题讨论】:
-
好吧,我们想看看你的尝试是什么,你在哪里遇到问题。我们不会为您做,但如果您有一些具体问题,我们可以提供帮助
-
尝试在代码沙箱中进行,然后您可以分享您的代码,我们可以提供更多帮助!
-
当您的问题得到解答后,请不要将其更新为“已解决”并删除代码。这将导致任何人在以后来这里寻求答案时都会感到迷茫并且不知道他们在看什么。
标签: javascript reactjs react-functional-component