reactjs - 如何在反应 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>
谢谢。
解决方案
不知道你到底想做什么,但我认为这应该可以帮助你
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
推荐阅读
- node.js - 使用对话框流(node.js)的“importAgent”接口时出错
- terraform - 自定义地形模块
- content-management-system - 为大型高负载解决方案选择哪种基于 .Net 的 CMS
- windows - Packer 构建在自动生成密码时超时
- arrays - 如何在 C 中弄乱指向字符串数组的指针的顺序?
- html - 删除 2 个表格元素之间不需要的间距 ( )
- pandas - 将列附加到同一数据框中的另一个类似列表的列
- java - 是否可以将标记继承与 apache wicket 面板一起使用
- windows - 无论如何,“替换进程级别令牌”是什么?
- linux - 每秒执行一个命令,同时考虑命令运行的时间