reactjs 如何增加和减少计数通过点击按钮在React?

368yc8dk  于 2023-04-29  发布在  React
关注(0)|答案(5)|浏览(157)

我想创建一个递增和递减计数器,但我不明白这件事,请帮助我

const [quantity, setQuantity] = useState()
      const handleIncrement = () => {
        if (quantity < 20) {
          setQuantity()
        }
      }
      const handleDecrement = () => {
        if (quantity > 1) {
          setQuantity()
        }
      }
yhxst69z

yhxst69z1#

const [quantity, setQuantity] = useState(0)
      const handleIncrement = () => {
        if (quantity < 20) {
          setQuantity(quantity - 1)
        }
      }
      const handleDecrement = () => {
        if (quantity > 1) {
          setQuantity(quantity + 1)
        }
      }
nhaq1z21

nhaq1z212#

一个示例代码,用于您对react Hooks“useState”的理解。‎

function App() {
  const [counter, setCounter] = useState(1);
  const incrementCounter = () => setCounter(counter + 1);
  let decrementCounter = () => setCounter(counter - 1);
  if(counter<=0) {
    decrementCounter = () => setCounter(1);
  }
  return (
    <div> 
      <ButtonIncrement onClickFunc={incrementCounter}/>
      <Display message={counter}/> 
      <ButtonDecrement onClickFunc={decrementCounter}/>
    </div>
  );
}
i7uaboj4

i7uaboj43#

react中的useState钩子返回一个有状态值,以及一个更新它的函数。在这种情况下,setQuantity函数用于更新状态。它接受一个新的状态值,并将组件的重新呈现排入队列。
它应该这样使用:setQuantity(newValue);
在你的代码中正确的方法可能是:

const [quantity, setQuantity] = useState(1)

      const handleIncrement = () => {
        if (quantity < 20) {
          setQuantity(quantity + 1)
        }
      }

      const handleDecrement = () => {
        if (quantity > 1) {
          setQuantity(quantity - 1)
        }
      }

我想有一些概念你错过了,如果你想知道更多,请看看https://reactjs.org/docs/hooks-reference.html:)

hlswsv35

hlswsv354#

您应该首先定义一个默认状态

const [quantity, setQuantity] = useState(0)

之后,您可以使用setQuatity函数的数量或先前状态。

const handleIncrement = () => {
      setQuantity(prev=>prev++)
      // or
      setQuantity(quantity++)
    }
  }

 const handleIncrement = () => {
      // add logic to prevent negative count here
      setQuantity(prev=>prev--)
      // or
      setQuantity(quantity--)
    }
  }
4xrmg8kj

4xrmg8kj5#

import React, { Component } from "react"

class Test extends Component { state = { count: 1, }

onIncrement = () => { this.setState((prevState) => { return { count: prevState.count + 1 } }) }

onDecrement = () => { this.setState((prevState) => { return { count: prevState.count - 1 } }) }

render() { return ( {this.state.count} Increment Decrement ) } }

相关问题