Untitled
unknown
typescript
2 years ago
1.8 kB
5
Indexable
interface IPieceProps { color: string; zIndex: number; description: string; } class Piece { color: string; zIndex: number; description: string; constructor(props: IPieceProps) { this.color = props.color; this.zIndex = props.zIndex; this.description = props.description; } } const Grid = () => { const [pieces, setPieces] = React.useState<Piece[]>([]); const addPiece = () => { setPieces([...pieces, new Piece({ color: "black", zIndex: pieces.length, description: "Pawn" })]); }; const removePiece = (index: number) => { setPieces(pieces.filter((_, i) => i !== index)); }; const movePiece = (index: number, newIndex: number) => { setPieces( pieces.map((piece, i) => { if (i === index) { return { ...piece, zIndex: newIndex }; } return piece; }) ); }; return ( <div style={{ display: "grid", gridTemplateColumns: "repeat(8, 1fr)", gridGap: "10px" }}> {pieces.map((piece, i) => ( <div key={i} style={{ backgroundColor: piece.color, zIndex: piece.zIndex, display: "flex", justifyContent: "center", alignItems: "center", height: "50px", width: "50px", position: "relative", }} > <div style={{ position: "absolute", bottom: "100%", left: "50%", transform: "translateX(-50%)" }} title={piece.description} /> </div> ))} <button onClick={addPiece}>Add Piece</button> <button onClick={() => removePiece(pieces.length - 1)}>Remove Piece</button> <button onClick={() => movePiece(pieces.length - 1, pieces.length)}>Move Piece</button> </div> ); };
Editor is loading...