为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 React.js 项目中将类组件转换为功能组件?

如何在 React.js 项目中将类组件转换为功能组件?

慕田峪7331174 2023-07-06 15:29:23
在我观看的项目中,他们使用类组件,但我想使用钩子使用功能组件来执行这些操作。你们能如何帮助我?我尝试了很多次,但无法完成这个翻译。我还在努力我的代码(导入的数据是“成分”):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
查看完整描述

1 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

我无法测试它,但对你来说是一个好的开始,我使用 ES6 语法......


import React, { useState } from 'react';

import { Hamburger, TotalPrice, ItemList } from './SuperComponents.jsx';


const App = () => {

    const [ingredients, setIngredients] = useState([]);

    // You are not using this state

    // const [totalPrice, setTotalPrice] = useState(0);


    const addIngredients = (product) => {

        setIngredients([...ingredients, { ...product, displayId: Math.random() }]);

    };


    const removeIngredients = (product) => {

        const selectedProduct = ingredients.find(

            (ingredient) => ingredient.name === product.name

        );


        const { targetId } = selectedProduct;

        setIngredients(

            ingredients.filter((ingredient) => ingredient.displayId !== targetId)

        );

    };

    const calculateTotal = () => {

        let total = 4;

        ingredients.forEach((item) => (total += item.price));

        return total.toFixed(2);

    };

    return (

        <>

            <Hamburger ingredients={ingredients} />

            <TotalPrice total={() => calculateTotal()} />

            <ItemList

                items={ingredients}

                addIngredients={(i) => addIngredients(i)}

                removeIngredients={(i) => removeIngredients(i)}

                selectedIngredients={ingredients}

            />

        </>

    );

};


export default App;


查看完整回答
反对 回复 2023-07-06
  • 1 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信