简体   繁体   English

onClick function 内的计数器

[英]Counter inside an onClick function

I have a button that adds a new div (onClick).我有一个添加新 div 的按钮(onClick)。 I want to add +1 to cargoNumberCounter so that it shows that it's a new div.我想为 cargoNumberCounter 添加 +1 以显示它是一个新的 div。


  const [addReference, setAddReference] = useState([])
  const [cargoNumberCounter, setCargoNumberCounter] = useState(1)

  const createNewRef = () => {
    setCargoNumberCounter(cargoNumberCounter + 1)

    const newRef = (
      <div>
          <Heading>
             Cargo # {cargoNumberCounter}
            // {cargoNumberCounter.map((num, i) => (
            //  <p key={i}>Cargo # {num}</p>
            // ))}
          </Heading>
          <Button onClick={createNewRef}>
             Add more cargo
          </Button>
      </div>
    )

    setAddReference((ref) => [...ref, newRef])
  }

I thought I could make it work like I have shown in the example, or by spreading the state like so setCargoNumberCounter([...cargoNumberCounter, cargoNumberCounter +1]) , but for some reason it doesn't work.我想我可以让它像我在示例中显示的那样工作,或者通过像setCargoNumberCounter([...cargoNumberCounter, cargoNumberCounter +1])那样传播 state ,但由于某种原因它不起作用。

Any thoughts on how to add +1 to each new div?关于如何为每个新 div 添加 +1 的任何想法?

It sounds like you may be better off with one button to add new items of cargo to the list.听起来您最好用一个按钮将新的货物添加到列表中。 Here's a quick example.这是一个简单的例子。

 const { useState } = React; function Example() { // Simple counter in state. You may prefer this to be // an array, or an object that you can add item objects to const [counter, setCounter] = useState(0); // Returns an array of divs based on the counter value function getDivs() { const divs = []; for (let i = 0; i < counter; i++) { divs.push(<div>{i + 1}</div>); } return divs; } // Updates the counter function handleClick() { setCounter(counter + 1); } return ( <div> <div className="divs"> {getDivs()} </div> <div className="counter">Div count: {counter}</div> <button type="button" onClick={handleClick}> Add new div </button> </div> ); } ReactDOM.render( <Example />, document.getElementById('react') );
 .divs { border: 1px solid #676767; padding-left: 0.3em; }.divs, .counter { margin-bottom: 1em; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM