首页 > 解决方案 > 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

标签: javascriptreactjsreact-hooksuse-state

解决方案


问题是你click在你的条件语句中,你只有一个clickstate`,所以自然它们都会同时切换。

要解决此问题,您应该为要切换的所有元素拥有唯一的状态。

例子:

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>
  ));
}

编辑 react-how-to-prevent-activating-all-icons-on-1-click


推荐阅读