javascript - React-如何防止一键激活所有图标
问题描述
如何防止一键激活所有图标?
import React, { useState} from 'react'
import { FaPlus, FaMinus} from 'react-icons/fa'
function App2() {
const [click, setClick] = useState(false)
function handleClick() {
setClick(!click)
}
return (
<>
<div onClick={ handleClick}>
{click ? <FaPlus /> : <FaMinus />}
{click ? <FaPlus /> : <FaMinus />}
{click ? <FaPlus /> : <FaMinus />}
{ click ? <FaPlus/> : <FaMinus/>}
</div>
</>
)
}
export default App2
解决方案
问题是你click
在你的条件语句中,你只有一个click
state`,所以自然它们都会同时切换。
要解决此问题,您应该为要切换的所有元素拥有唯一的状态。
例子:
import React, { useState } from "react";
import { FaPlus, FaMinus } from "react-icons/fa";
function App2() {
// Use an array to store each click boolean
const [clicks, setClicks] = useState(new Array(4).fill(false));
const handleClick = (index) => () => {
// Map the previous array of booleans to a new array
// Toggle the element at the specific index
setClicks((click) => click.map((el, i) => (i === index ? !el : el)));
};
// Map the array of click booleans
// Assing a div and onClick to each pair of "+"/"-" icons
return clicks.map((click, i) => (
<div onClick={handleClick(i)}>{click ? <FaPlus /> : <FaMinus />}</div>
));
}
推荐阅读
- c# - Process.Start 使用 ServiceUser 凭据进行模拟/在 ServiceUser 的上下文中运行代码(没有机器的登录权限)
- html - 使用 css 制作弯曲边缘
- java - 如何找出一个词是在某些特定词之前还是之后
- conda - 了解 conda 冲突解决消息
- ffmpeg - 带有 VP9 + RTSP 的 FFMPEG
- c++ - 将 shared_ptr 的向量转换为 C++ 中的原始指针向量
- angular - 当在构造函数中提到服务时,Angular 中缺少组件,在组件本身内部未使用。JHipster 应用程序
- c# - 切换到主屏幕前的闪屏显示突然运动
- reactjs - React Redux 组件传递道具不重新渲染
- docker - Docker swarm 任务状态 Failed VS Rejected