【问题标题】:How do I convert Class Components to Functional Components in React.js project?如何在 React.js 项目中将类组件转换为功能组件?
【发布时间】: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


【解决方案1】:

纳瓦罗我希望这对你有帮助!我无法测试它,但对你来说是一个好的开始,我使用 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2020-02-08
    • 2020-06-22
    • 2021-05-29
    相关资源
    最近更新 更多