我有 2 个按钮和 1 个 h1,我需要计算按钮被单击的次数并显示带有编号的按钮名称。它在 h1 中单击的次数以及按钮的名称。现在我可以正确获取按钮的名称,但无法显示按钮的点击次数。请帮忙
import React, { Component, Fragment } from 'react'
import ReactDOM from 'react-dom'
export default class App extends Component {
state={
button:"",
countClick:0
}
buttonClick=(e)=>{
e.preventDefault();
this.setState({button:e.target.name, countClick:this.state.countClick+1});
}
render() {
return (
<Fragment>
<h1>
{this.state.button} clicked {this.state.countClick} times
</h1>
<button name="Button 1" type="button" onClick={this.buttonClick}>Button 1</button>
<button name="Button 2" type="button" onClick={this.buttonClick}>Button 2</button>
</Fragment>
)
}
}
ReactDOM.render(<App />,document.getElementById('root'));
谢谢
最佳答案
一些注意点:
- 构建一个数组来存储每个按钮的点击量状态。
- 可以选择使用
{id, value}
数组项的结构,因为我们需要显示单击的按钮及其单击量。 - 使用
map()
以免重复<button />
. - 将身份索引作为参数传递到嵌套处理函数内。
完整代码:
import React from "react";
import "./styles.css";
const amount = 2;
export default function App() {
const [clickList, setClickList] = React.useState(
[...Array(amount).keys()].map(x => ({ id: `Button ${x + 1}`, value: 0 }))
);
const [activeButton, setActiveButton] = React.useState("");
const buttonClick = idx => e => {
const result = [...clickList];
result[idx].value += 1;
setClickList(result);
setActiveButton(e.target.name);
};
return (
<>
<h1>
{`${activeButton} clicked ${clickList.find(x => x.id === activeButton)?.value ?? 0} times`}
</h1>
{clickList.map((x, idx) => (
<button name={x.id} type="button" onClick={buttonClick(idx)}>
{x.id}
</button>
))}
</>
);
}
关于javascript - React JS 哪个按钮被点击了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61292867/