简体   繁体   English

如何在 React 中实现多个按钮,当您单击一个按钮时,所有其他按钮都被取消选择

[英]How to implement multiple buttons in React and when you click one button, all the other buttons are deselected

I was trying to implement 3 buttons such that once one is clicked, it changes background colour, and the other 2 buttons are deselected and their background colour is reverted back to the original colour.我试图实现 3 个按钮,这样一旦单击一个按钮,它就会更改背景颜色,而取消选择其他 2 个按钮,它们的背景颜色将恢复为原始颜色。

However, when I tried to implement it in React, it was perptually 1 button behind (in the sense if I clicked button 1, 3, 2 in that order, I'd have the selected button as 1, 3 (not a typo, it's just behind)).但是,当我尝试在 React 中实现它时,它总是落后 1 个按钮(从某种意义上说,如果我按顺序单击按钮 1、3、2,我会将选定的按钮设置为 1、3(不是错字,它就在后面))。

Here's my code for that specific component.这是我针对该特定组件的代码。

import React, { useEffect } from "react";
import '../output.css'
import Full from '../Logos/Full.png';
import logo from "../logo.svg";
import Images from "./Images";
import { ImageLogo as Img } from "./Images";

export default function Events() {

    const button_colour = "bg-red-700";

    let [colour, setColour] = React.useState("");
    let [colour1, setColour1] = React.useState("");
    let [colour2, setColour2] = React.useState("");

    const [backgroundColor, setBackgroundColor] = React.useState('transparent');
    const [backgroundColor1, setBackgroundColor1] = React.useState('transparent');
    const [backgroundColor2, setBackgroundColor2] = React.useState('transparent');

    function handleClick(i: number) {
        console.log(`${i} and ${backgroundColor} and ${backgroundColor1} and ${backgroundColor2}`)
        switch (i) {
            case 0:
                setBackgroundColor(button_colour);
                setBackgroundColor1('transparent');
                setBackgroundColor2('transparent');
            case 1:
                setBackgroundColor('transparent');
                setBackgroundColor1(button_colour);
                setBackgroundColor2('transparent');
            case 2:
                setBackgroundColor('transparent');
                setBackgroundColor1('transparent');
                setBackgroundColor2(button_colour);
        }
    }

    // Create 3 refs
    const ref1 = React.useRef(null);
    const ref2 = React.useRef(null);
    const ref3 = React.useRef(null);

    const refs = [ref1, ref2, ref3];

    useEffect(() => {
        // console.log(colour);
    }, [colour, colour1, colour2]);

    const changeColour = (index: number) => {
        let newColour = [colour, colour1, colour2];
        for (let i = 0; i < 3; i++) {
            if (i !== index) {
                newColour[i] = "";
            } else {
                newColour[i] = button_colour;
            }
        }

        // Remove button_colour from all refs
        for (let i = 0; i < 3; i++) {
            if (refs[i].current) {
                refs[i].current.className = refs[i].current.className.replace(button_colour, "");
            }
        }

        setColour(newColour[0]);
        setColour1(newColour[1]);
        setColour2(newColour[2]);
        console.log(newColour);
        if (ref1.current) {
            ref1.current.className += " " + colour;
        }
        if (ref2.current)
            ref2.current.className += " " + colour1;
        if (ref3.current)
            ref3.current.className += " " + colour2;
        console.log(`Colours are ${colour}, ${colour1}, ${colour2}`);
    }

    const k = (i: number) => {
        // console.log(`Hi, it's ami ${colour}, ${colour1}, ${colour2}`);
        return 1;
    }

    return (
        <div className="">
            <h1 className="text-white font-bold text-center">EVENT SCHEDULE</h1>
            <div className="Dates flex text-yellow-800 font-bold justify-center h-15-s">
                {/* <p className="w-1.5/12 text-center h-4/6 hover:button_colour rounded-md" onClick={e => changeColour(0)} ref={ref1}>January 10th</p> */}
                {/* <button onClick={e => handleClick(0)} style={{ backgroundColor }}>January 10th</button>
                <button onClick={e => handleClick(1)} style={{ backgroundColor: backgroundColor1 }}>January 11th</button>
                <button onClick={e => handleClick(2)} style={{ backgroundColor: backgroundColor2 }}>January 12th</button> */}
                <p className="w-1.5/12 text-center h-4/6 hover:button_colour rounded-md" onClick={e => changeColour(0)} ref={ref1}>January 11th</p>
                <p className="w-1.5/12 text-center h-4/6 hover:button_colour rounded-md" onClick={e => changeColour(1)} ref={ref2}>January 11th</p>
                <p className="w-1.5/12 text-center h-4/6 hover:button_colour rounded-md" onClick={e => changeColour(2)} ref={ref3}>January 12th</p>
            </div>
            {/* {colour[0] !== "" && k(0) && <Images />}
            {colour[1] !== "" && k(1) && <Img />}
            {colour[2] !== "" && k(2) && <Img />} */}
        </div>
        
    );
}

The components which I imported from './Images' are simply components which have <img src={<Image_here>} /> .我从'./Images'导入的组件只是具有<img src={<Image_here>} />的组件。

Maintain a state for activeBtnElement, and when you click a particular button update this activeBtnElement state with that.为 activeBtnElement 维护一个 state,当你点击一个特定的按钮时更新这个 activeBtnElement state。 Then apply conditions based on this state. You can also use buttonGroup.然后根据这个state申请条件,也可以用buttonGroup。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将单个单击事件绑定到多个按钮时,如何使被单击的按钮做一件事,而其他所有按钮做另一件事? - When binding a single click event to multiple buttons, how can I make the clicked button do one thing and all the other buttons do another? jQuery多个按钮以显示相同的表单,只需单击一个按钮即可触发所有按钮的表单 - jquery multiple buttons to display same form is triggering forms for all buttons with one button click 如何激活模式以在所有3个按钮上单击而不仅仅是在一个按钮上打开? - How to activate modal to open on all 3 buttons click and not just with one button? 当我单击香草javascript中的其他按钮时,从所有其他按钮中删除ACTIVE类 - Remove ACTIVE classes from all other buttons when I click an other button in vanilla javascript 如何使用多个按钮更改按钮颜色 - How to Change Button Colors on Click with Multiple Buttons 如何一键重置所有按钮的值 - How to reset the value of all buttons with one button 在按钮上选择/取消选择设置 - setting selected/deselected on buttons 如何重置所有其他按钮的背景颜色并在单击时突出显示所选按钮? - How to reset the background colour of all other buttons and highlight the selected button when clicked? 单击一个新按钮时,如何将组中的所有其他图像按钮“重置”到上一个图像 - How to have all other image buttons in group “reset” to previous image when a new button is clicked HTML按钮,单击按钮时进行切换,并切换所有其他按钮(折叠信息) - HTML buttons, toggle when button clicked and toggle all other buttons (collapse info)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM