【问题标题】:React - Individual Counter Components - Parent Increase/Decrease AllReact - 单个计数器组件 - 父级增加/减少所有
【发布时间】:2020-08-27 01:48:05
【问题描述】:

警告:对仍在学习的新手做出反应。

我有一个挑战,需要我构建一个简单的 React Counter 应用程序。规则是:不使用 Redux,不使用钩子。每个计数器都独立地通过单击按钮来增加或减少。和! Parent 组件可以递增或递减所有 Counter 组件。

单个递增/递减的EX:

计数器 1 = 2

计数器 2 = 4

计数器 3 = 6

EX Increment ALL 将进行以下更改:

计数器 1 = 3

计数器 2 = 5

计数器 3 = 7

我知道这涉及在父组件中定义的回调函数,我只是对如何实现它感到困惑。我现在有一种非常低效的方法来做到这一点。谁能引导我以更有效的方式进行设置?

这是我的父母

import React from 'react';
import Counter from './components/Counter';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.counterElement1 = React.createRef();
    this.counterElement2 = React.createRef();
    this.counterElement3 = React.createRef();
  }

  handleAllIncrease = () => {
    console.log("hello App Increase")
    this.counterElement1.current.handleIncrease();
    this.counterElement2.current.handleIncrease();
    this.counterElement3.current.handleIncrease();
  }

  handleAllDecrease = () => {
    console.log("hello App Decrease")
    this.counterElement1.current.handleDecrease();
    this.counterElement2.current.handleDecrease();
    this.counterElement3.current.handleDecrease();
  }

  render() {
    return (
      <div className="App">
        <button onClick={() => this.handleAllIncrease()}>Increase all</button>
        <button onClick={() => this.handleAllDecrease()}>Decrease all</button>
          <Counter  ref={this.counterElement1} />
          <Counter  ref={this.counterElement2}/>
          <Counter  ref={this.counterElement3}/>
      </div>
    );
  }
}

export default App;

这是我的孩子

import React from 'react';


class Counter extends React.Component {


    state = {
        num: 0,
    }

    handleIncrease = () => {
        console.log("hello increase")
        this.setState({
            num: this.state.num + 1,
        })

    }

    handleDecrease = () => {
        console.log("hello decrease")
        this.setState({
            num: this.state.num - 1,
        })
    }

    render() {
        return (
            <div>
                <p>{this.state.num}</p>
                <button onClick={this.handleIncrease}>+</button>
                <button onClick={this.handleDecrease}>-</button>
            </div>
        )
    }
}

export default Counter;

【问题讨论】:

    标签: reactjs components parent-child counter


    【解决方案1】:

    正如你所说,你是一个新手,所以不会尝试任何花哨的东西并尝试找到一个简单的解决方案。

    让我们有一个父组件 App 定义为

    class App extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = {
          counterA: 0,
          counterB: 0,
          counterC: 0
        }
      }
    
      handleAllIncrement = () => {
        this.setState(prevState => ({
          counterA: prevState.counterA + 1,
          counterB: prevState.counterB + 1,
          counterC: prevState.counterC + 1
        }))
      }
    
      handleAllDecrement = () => {
        this.setState(prevState => ({
          counterA: prevState.counterA - 1,
          counterB: prevState.counterB - 1,
          counterC: prevState.counterC - 1
        }))
      }
    
      render() {
        return (
          <Fragment>
            <div style={{display: 'flex', justifyContent: 'space-evenly'}}>
              <Counter counter={this.state.counterA} />
              <Counter counter={this.state.counterB} />
              <Counter counter={this.state.counterC} />
            </div>
            <br />
            <div style={{textAlign: 'center'}}>
              <button onClick={this.handleAllIncrement}> + All </button>
              <button onClick={this.handleAllDecrement}> - All </button>
            </div>
          </Fragment>
        );
      }
    }
    

    它包含两个方法handleAllIncrement 和handleAllDecrement,它们将递增所有状态变量的值,否则,这是父组件的目标。它还将具有三个变量/状态变量,它们将被传递给各个计数器组件。

    counterA: 0,
    counterB: 0,
    counterC: 0
    

    现在,让我们看看子组件的作用。

    import React from "react";
    
    class Counter extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          num: 0
        };
      }
    
      handleIncrease = () => {
        this.setState(prevState => ({
          num: prevState.num + 1
        }));
      };
    
      handleDecrease = () => {
        this.setState(prevState => ({
          num: prevState.num - 1
        }));
      };
    
      render() {
        return (
          <div>
            <p>{this.state.num + this.props.counter}</p>
            <button onClick={this.handleIncrease}>+</button>
            <button onClick={this.handleDecrease}>-</button>
          </div>
        );
      }
    }
    
    export default Counter;
    
    

    最初,我们定义一个状态变量 num ,当单独执行递增和递减时会更改它。

    其余的东西都是正常反应的东西,我应用的唯一技巧就是线

    <p>{this.state.num + this.props.counter}</p>
    

    这一行的作用是将父级传递的任何值添加到当前状态值。

    因此,计数器 A 单独递增两次,因此 A 的 num 现在为 2。 您现在单击了三次递增所有按钮,现在将发生的情况是 num + props.counter(即现在为 3)将给出 5,而另一个将有 3,因为单个状态为 0 + 传递的值为 3。

    这里是运行代码如果你想玩Example

    【讨论】:

    • 哦!好的,我明白了!是的,这完全有道理。非常感谢您的帮助和详尽的解释!
    • 很高兴知道它有帮助 ^.^
    【解决方案2】:

    好的,我建议在父元素中包含所有功能。然后在里面定义4个函数,handleIncrease,handleDecrease,handleIncreaseAll,handleDecreaseAll。然后我会有一个带有计数器的数组,为每个计数器都有一个索引以及它具有的相应的增加/减少值。 在handleIncrease 以及handleDecrease 中,您应该传递一个参数来确定当前计数器的索引并知道它应该增加/减少多少。最后,您应该将这些函数作为道具传递给计数器,并且在 Counter 中每个增加/减少按钮的 onClick 事件中,您应该根据具体情况引用 props.handleIncrease 或 props.handleDecrease。

    【讨论】:

      【解决方案3】:

      尝试使用备忘录。这有助于维护每个子组件的缓存。

      react-hook

      【讨论】:

      • 她提到没有使用钩子。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2018-07-25
      • 2013-05-17
      相关资源
      最近更新 更多