如何在 react ts 的单个 onClick 计数上制作多个按钮?
How to make a multiple button on a single onClick count in react ts?
我遇到了这个问题,有几个计数会在点击时增加。
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>
);
}
你可以运行这里的codesandbox https://codesandbox.io/s/dank-mountain-bmkgi
我遇到了这个问题,有几个计数会在点击时增加。
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>
);
}
你可以运行这里的codesandbox https://codesandbox.io/s/dank-mountain-bmkgi