【问题标题】:Increment / Decrement function in ReactJSReactJS 中的递增/递减函数
【发布时间】:2020-08-18 05:36:22
【问题描述】:

我创建了一个递增/递减函数,但我有疑问。

我可以减少点击包含递增计数的同一个按钮的计数吗? 如何创建该功能?

代码:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      clicks: 0,
      show: true
    };
  }

  IncrementItem = () => {
    this.setState({ clicks: this.state.clicks + 1 });
  }
  DecreaseItem = () => {
    this.setState({ clicks: this.state.clicks - 1 });
  }
  ToggleClick = () => {
    this.setState({ show: !this.state.show });
  }

  render() {
    return (
      <div>
        <button onClick={this.IncrementItem}>Click to increment by 1</button>
        <button onClick={this.DecreaseItem}>Click to decrease by 1</button>
        <button onClick={this.ToggleClick}>
          { this.state.show ? 'Hide number' : 'Show number' }
        </button>
        { this.state.show ? <h2>{ this.state.clicks }</h2> : '' }
      </div>
    );
  }
}

export default App;

【问题讨论】:

  • 嗨,您能否更清楚地解释您正在尝试做什么,或者您想要做什么,或者可能无法按预期工作?很不清楚你在问什么。
  • 是的,好的。例如:Instagram 上的点赞按钮。只要我点击按钮,它就会添加一个赞,当我点击同一个赞按钮时,这个赞就会被删除。
  • 所以...基本上是一个切换?布尔状态?.....有一些全局状态计数,您想要一个按钮来添加+1(如果启用),+0(如果不启用)?
  • 是的,我正在尝试这样做!

标签: reactjs increment


【解决方案1】:

您可以在单击按钮时触发的函数中设置条件。也许是这样的:

从'react'导入反应,{组件};

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
      clicked: false,
    };
  }

  toggleClicked = () => {
      const counter = this.state.clicked ? counter +1 : counter - 1;
      const clicked = !this.state.clicked;

      this.setState({ counter, clicked })
  }

  render() {
    return (
      <div>
        <button onClick={this.toggleClicked}>Click</button>

        { this.state.counter ? <h2>{ this.state.counter }</h2> : '' }
      </div>
    );
  }
}

export default App;

这样,如果您已经点击了计数器,则计数器会减少 1,反之亦然。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多