Reactjs 如何在react ts中的单个onClick计数上创建多个按钮?
我有这个问题,点击几次就可以增加计数Reactjs 如何在react ts中的单个onClick计数上创建多个按钮?,reactjs,react-hooks,increment,Reactjs,React Hooks,Increment,我有这个问题,点击几次就可以增加计数 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 cou
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>
let count=[{id:1,值0},{id:2,值0}]
常量[计数器,设置计数器]=使用状态(计数器)
增量=()=>{
我想设置计数器值取决于点击按钮,计数器只会在上面的特定计数上加1。
}
返回
{count1}不确定你到底想做什么,但我认为这应该能帮到你
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>
);
}
import React,{useState}来自“React”;
导入“/styles.css”;
导出默认函数App(){
让计数={
1: 0,
2: 0
};
常量[计数器,设置计数器]=使用状态(计数);
常量增量=(id)=>{
setCounter({…计数器[id]:计数器[id]+1})
};
返回(
{增量(1)}}>+
{增量(2)}}>+
);
}
您可以在此处运行codesandbox使用对象作为您的状态,而不是Int。您的意思是?const[counter,setCounter]=useState({count1:0,count2:0})是。然后在设置计数器时,重置整个对象:setCounter({count1:2,…counter})