首页 > 解决方案 > 如何在反应 ts 中在单个 onClick 计数上制作多个按钮?

问题描述

我遇到了这个问题,点击时要增加几个计数。

let count = [{id: 1, value 0}, {id: 2, value 0}]

const [counter,setCounter] = useState(counter)

increment = () => {
   I want to set counter value depends on the button click and the counter will add 1 only to the specific count above.
}

return <div>
         <input type='text' value='count1'>{count1}</h2> <- I know that this does not work
         <button onClick={increment()}>+</button>
         <input type='text' value='count1'>{count2}</h2>
         <button onClick={increment()}>+</button>

谢谢。

标签: reactjsreact-hooksincrement

解决方案


不知道你到底想做什么,但我认为这应该可以帮助你

import React, { useState } from "react";
import "./styles.css";

export default function App() {
    let count = {
        1: 0,
        2: 0
    };
    const [counter, setCounter] = useState(count);
    const increment = (id) => {
        setCounter({ ...counter, [id]: counter[id] + 1 })
    };
    
    return (
        <div className="App">
            <input type='text' id="1" value={counter[1]}></input>
            <button onClick={() => { increment(1) }}>+</button>
            <input type='text' id="2" value={counter[2]}></input>
            <button onClick={() => { increment(2) }}>+</button>
        </div>
    );
}

您可以在此处运行代码和框https://codesandbox.io/s/dank-mountain-bmkgi


推荐阅读