简体   繁体   中英

Only one div active at a time in reactjs

I have three div in a row and three rows, In a row we select only one div at a time, another div is select the before div will unselect. my code like

 <div className="row">
    <div className="heil select"><button>Click One</button></div>
    <div className="heil"><button>Click Two</button></div>
    <div className="heil"><button>Click Three</button></div>
</div>
<div className="row">
    <div className="heil select"><button>Click One</button></div>
    <div className="heil"><button>Click Two</button></div>
    <div className="heil"><button>Click Three</button></div>
</div>
<div className="row">
    <div className="heil select"><button>Click One</button></div>
    <div className="heil"><button>Click Two</button></div>
    <div className="heil"><button>Click Three</button></div>
</div>

select class is used to click div will highlight, here statically write how this done in react and in a row we select only one div like radio button I am new in react-js, Please solve this Problem, thanks in advance

I just wrote a working example of what you want.

import { useState } from "react";

export default function Rows() {
const numberOfRows = 3;
const rows = Array(numberOfRows).fill(0);
const cellsEachRow = ["Click One", "Click Two", "Click Three"];
const [selectedCellsIndexes, setSelectedCellsIndexes] = useState(
    Array(numberOfRows).fill(0)
);
const handleCellClick = (parentIndex, childIndex) => {
    setSelectedCellsIndexes((selectedCellsIndexes) => {
        selectedCellsIndexes[parentIndex] = childIndex;
        return [...selectedCellsIndexes];
    });
};
return (
    <div>
        {rows.map((row, parentIndex) => {
            return (
                <div className="row">
                    {cellsEachRow.map((name, childIndex) => {
                        return (
                            <div
                                className={`heil ${
                                    childIndex ===
                                        selectedCellsIndexes[parentIndex] &&
                                    "selected"
                                }`}
                                onClick={() =>
                                    handleCellClick(parentIndex, childIndex)
                                }
                            >
                                <button>{name}</button>
                            </div>
                        );
                    })}
                </div>
            );
        })}
    </div>
);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM