React JS:将状态传递给父组件

时间:2018-09-16 19:33:53

标签: reactjs

我很难理解React组件并访问它们的数据。

假设我们有这样的东西:

import React, {Component} from 'react';

class Item extends React.Component {
        constructor(props) {
            super(props)

            this.state = {
                count: 0,
                sum: 0
            }
            this.increaseCount = this.increaseCount.bind(this);
        }

        increaseCount(e) {
            this.setState({
                count: this.state.count + 1
            });
            this.sumPerItem();
        }

        sumPerItem = () => {
            this.setState((s) => ({
                sum: s.count * this.props.price
            }))
        }

    render() {  
        return (
            <div>
            {this.props.price}<span>x{this.state.count}<button onClick={this.increaseCount}>+</button>={this.state.sum}</span>
            </div>
        )
    }
}

export default Item;

然后有一个父组件:

import React, { Component } from 'react';
import Item from './item';

class Calculator extends React.Component {
    constructor(props) {
      super(props)

      this.state = {
        total: 0
      }
 }

render() {
      return (
        <div>
          <Item price="3"/>
          <Item price="5"/>
          <Item price="7"/>
            <div>{this.state.total}</div>
        </div>
      )
    }
  }

  export default Calculator;

现在,我要访问各个“ sum”,这取决于道具“ price”而各不相同...

解决此问题的正确方法是最佳方法?

很抱歉,这是愚蠢的问题。我不是编码员或类似的人。只是对React及其所有内容感到好奇。

0 个答案:

没有答案
相关问题