通过 Material UI ButtonGroup 增加和减少按钮

Increment and Decrement button via Material UI ButtonGroup

我想用 material ui ButtonGroup 创建一个递增/递减按钮。按钮最初是这样的图像。

当用户点击按钮时,ButtonGroup 的第二部分将显示(如下图所示)。

我怎样才能做到这一点?请帮助。

提前致谢。

代码

import React from "react";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import ButtonGroup from "@material-ui/core/ButtonGroup";

class GroupedButtons extends React.Component {
  state = { counter: 0 };

  handleIncrement = () => {
    this.setState(state => ({ counter: state.counter + 1 }));
  };

  handleDecrement = () => {
    this.setState(state => ({ counter: state.counter - 1 }));
  };
  render() {
    const Btn = (
     <>
      <Button disabled>{this.state.counter}</Button>
      <Button onClick={this.handleDecrement}>-</Button>
     </>
    );

    return (
      <ButtonGroup size="small" aria-label="small outlined button group">
        <Button onClick={this.handleIncrement}>+</Button>
        {this.state.counter > 0 && Btn}
      </ButtonGroup>
    );
  }
}

export default GroupedButtons;

类似于上面的代码。但它不起作用。

Material UI ButtonGroup 预计只有 Button children。您将 React.Fragment 作为 child.

传递

您可以这样更改代码:

import React from "react";
import Button from "@material-ui/core/Button";
import ButtonGroup from "@material-ui/core/ButtonGroup";

class GroupedButtons extends React.Component {
  state = { counter: 0 };

  handleIncrement = () => {
    this.setState(state => ({ counter: state.counter + 1 }));
  };

  handleDecrement = () => {
    this.setState(state => ({ counter: state.counter - 1 }));
  };
  render() {
    const displayCounter = this.state.counter > 0;

    return (
      <ButtonGroup size="small" aria-label="small outlined button group">
        <Button onClick={this.handleIncrement}>+</Button>
        {displayCounter && <Button disabled>{this.state.counter}</Button>}
        {displayCounter && <Button onClick={this.handleDecrement}>-</Button>}
      </ButtonGroup>
    );
  }
}

export default GroupedButtons;

在此处查看现场演示:

带钩子: 我使用(产品['countInStock'])作为库存数量

的例子
const [counter, setCounter] = useState(0);
return (
   <ButtonGroup size="small" aria-label="small outlined button group">

        <Button disabled={counter >= product['countInStock']} onClick={()=> 
        {setCounter(counter+1)}}>+</Button>

     {<Button disabled>{counter}</Button>}

      {<Button disabled={counter <= 0} onClick={() => {
        setCounter(counter - 1)
        }}>-</Button>}

  </ButtonGroup>
)