简体   繁体   English

如何从子组件更新我的父 state?

[英]How can I update my parent state from child component?

I'm currently developing a React app (ES6) whereby a number of food items will be listed.我目前正在开发一个 React 应用程序(ES6),其中将列出许多食品。

Each time a product has been clicked, the individual product count (child state) should increase by 1 each time, which currently works.每次单击产品时,单个产品计数(子状态)应每次增加 1,当前有效。

However, the total calorie count (parent state) should also increase using the data from the parent foods state.然而,总卡路里计数(父状态)也应该使用来自父食物 state 的数据增加。

Example: A user clicks on the Brussel Sprouts item.示例:用户单击布鲁塞尔芽菜项目。 The FoodItem count will increase by +1 on each click, however I also require the overall calorie count in the App class (this.state.calorieCount) to increment, by 28.1 on each click in this instance.每次点击时,FoodItem 计数将增加 +1,但是我还要求应用程序 class (this.state.calorieCount) 中的总卡路里计数在此实例中每次点击增加 28.1。

I'm fairly new to react so any help on this would be much appreciated.我是相当新的反应,所以对此的任何帮助将不胜感激。

// FoodCards.js // FoodCards.js

const FoodCards = [
    {
        id: 0,
        name: 'Brussel Sprouts',
        quantity: '1/2 cup',
        calories: 28.1,
        betacarotene: 0.363,
        bilberry_fruit: 0,
        curcumin: 0,
        grapeseed: 0,
        green_tea: 0, 
        lutein: 1,
        lycopene: 0,
        vitamin_a: 0.03,
        vitamin_d: 0
    },
    ...
];
export default FoodCards

// App.js // 应用程序.js

import React from 'react';
import './tailwind.output.css';
import './App.scss';
import FoodCards from './data/foods';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      foods: FoodCards,
      calorieCount: 0,
      vitaminACount: 0,
      vitaminDCount: 0,
    };
    this.increment = this.increment.bind(this);
  }

  increment(calories, vitaminA, vitaminD) {
    this.setState({
      calorieCount: Math.round(this.state.calorieCount + calories),
      vitaminACount: Math.round((this.state.vitaminACount + vitaminA) * 100) / 100,
      vitaminDCount: Math.round((this.state.vitaminDCount + vitaminD) * 100) / 100
    });
  };

  reset() {
    this.setState({
      calorieCount: 0,
      vitaminACount: 0,
      vitaminDCount: 0,
    });
  };

  render() {

    return (
      <div className="App">
        
        <header className="flex flex-wrap">
          <div className="calories-total">
            <span>Calories</span>
            <span className="num">{this.state.calorieCount}</span>
          </div>
  
          <div className="vitamin-a-total">
            <span>Vitamin A</span>
            <span className="num">{this.state.vitaminACount}</span>
          </div>
  
          <div className="vitamin-d-total">
            <span>Vitamin D</span>
            <span className="num">{this.state.vitaminDCount}</span>
          </div>
  
          <div className="export-btn flex items-center justify-center">
            Export Full Report
          </div>
  
        </header>
  
        <main className="products-grid flex flex-wrap">
  
        {this.state.foods.map((item, i) => {
          return <FoodItem key={item.id} name={ item.name } calories={item.calories} />
        })}
  
        </main>

        <footer>
          <div className="reset" onClick={() => this.reset()}>Reset</div>
        </footer>
  
      </div>
    );
  }
}

export default App;

class FoodItem extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      clickCount: 0
    };
  }

  handleClickIncrement() {
    this.setState({
      clickCount: this.state.clickCount + 1
    });
  };

  render() {
    return (
      <div className="product" onClick={() => this.handleClickIncrement()}>
        <p>{this.props.name} - {this.state.clickCount}</p>
        <p>Calories: {this.props.calories}</p>
      </div>
    );
  }
}

Your FoodItem needs a function with which it can notify the parent.您的 FoodItem 需要一个 function 来通知父母。 So in App you can give it something like this:所以在App中你可以给它这样的东西:

  <FoodItem
    updateParent={this.updateFromItem.bind(this)}
    // other props
  />

Also in the Parent也在父

  updateFromItem(calories) {
    this.increment(calories, 0, 0);
  }

The updateFromItem function sits within the parent component and via bind(this) it is scoped to it, but you propagate the change from the child (FoodItem) and call it from there: updateFromItem function 位于父组件内,并通过bind(this)作用于它,但是您从子组件 (FoodItem) 传播更改并从那里调用它:

  handleClickIncrement() {
    this.props.updateParent(this.props.calories);
    // ...
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM