如何在React中实现带彩色瓦片背景的图表并添加指定坐标点
Hey there! Let's walk through how to build this tile-based background with coordinate points in React. We'll keep it simple with plain React and CSS—no fancy external libraries needed. Here's a step-by-step breakdown:
First, we'll create a 4x4 grid using CSS Grid (perfect for 2D layouts like this). We'll define a set of custom colors for each tile, and add optional coordinate labels to make it easier to verify positions.
React Component (TileGrid.jsx)
import React from 'react'; import './TileGrid.css'; const TileGrid = ({ points = [] }) => { // Custom 4x4 tile color scheme—tweak these to your liking! const tileColors = [ ['#f0f9ff', '#e0f2fe', '#bae6fd', '#7dd3fc'], ['#dbeafe', '#bfdbfe', '#93c5fd', '#60a5fa'], ['#eff6ff', '#dbeafe', '#bfdbfe', '#93c5fd'], ['#f0f9ff', '#e0f2fe', '#bae6fd', '#7dd3fc'] ]; return ( <div className="tile-grid"> {tileColors.map((row, yIndex) => ( row.map((color, xIndex) => { // Convert array indexes (0-based) to your 1-4 coordinate system const tileX = xIndex + 1; const tileY = yIndex + 1; return ( <div key={`tile-${tileX}-${tileY}`} className="tile" style={{ backgroundColor: color }} > {/* Optional coordinate label for debugging */} <span className="tile-coord">{`(${tileX}, ${tileY})`}</span> {/* Render coordinate points if this tile matches any point in the props */} {points.some(point => point.x === tileX && point.y === tileY) && ( <div className="tile-point"></div> )} </div> ); }) ))} </div> ); }; export default TileGrid;
CSS Styling (TileGrid.css)
.tile-grid { display: grid; grid-template-columns: repeat(4, 1fr); /* 4 equal-width columns */ grid-template-rows: repeat(4, 1fr); /* 4 equal-height rows */ width: 400px; /* Adjust size as needed */ height: 400px; gap: 2px; /* Small gap between tiles */ background-color: #1e293b; /* Grid border color */ padding: 2px; border-radius: 8px; } .tile { display: flex; align-items: center; justify-content: center; border-radius: 4px; position: relative; } .tile-coord { font-size: 12px; color: #64748b; } .tile-point { width: 20px; height: 20px; border-radius: 50%; background-color: #ef4444; /* Bright red point—customize this! */ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* Center the point perfectly */ box-shadow: 0 0 8px rgba(239, 68, 68, 0.6); /* Optional glow effect */ }
Now we can import the TileGrid into a parent component and pass in our desired coordinate points (all x/y values between 1-4).
Parent Component Example (App.jsx)
import React from 'react'; import TileGrid from './TileGrid'; const App = () => { // Example coordinate points—add/remove these as needed const coordinatePoints = [ { x: 2, y: 3 }, { x: 4, y: 1 }, { x: 1, y: 4 } ]; return ( <div style={{ padding: '2rem', display: 'flex', flexDirection: 'column', gap: '1rem', alignItems: 'center' }}> <h2>Tile Grid with Coordinate Points</h2> <TileGrid points={coordinatePoints} /> </div> ); }; export default App;
Want to let users add points on the fly? Here's a quick addition to the parent component to handle input and validation:
import React, { useState } from 'react'; import TileGrid from './TileGrid'; const App = () => { const [points, setPoints] = useState([{ x: 2, y: 3 }]); const [newX, setNewX] = useState(''); const [newY, setNewY] = useState(''); const addPoint = (e) => { e.preventDefault(); const x = parseInt(newX); const y = parseInt(newY); // Validate coordinates are within 1-4 if (x >= 1 && x <= 4 && y >= 1 && y <= 4) { setPoints([...points, { x, y }]); setNewX(''); setNewY(''); } else { alert('Coordinates must be integers between 1 and 4!'); } }; return ( <div style={{ padding: '2rem', display: 'flex', flexDirection: 'column', gap: '1rem', alignItems: 'center' }}> <h2>Tile Grid with Coordinate Points</h2> {/* Form to add new points */} <form onSubmit={addPoint} style={{ display: 'flex', gap: '0.5rem' }}> <input type="number" placeholder="X (1-4)" value={newX} onChange={(e) => setNewX(e.target.value)} min="1" max="4" /> <input type="number" placeholder="Y (1-4)" value={newY} onChange={(e) => setNewY(e.target.value)} min="1" max="4" /> <button type="submit">Add Point</button> </form> <TileGrid points={points} /> </div> ); }; export default App;
- Coordinate Conversion: Remember that array indexes start at 0, so we add 1 to map them to your 1-4 coordinate system.
- Flexibility: Adjust the grid size, tile colors, and point styling by modifying the CSS and
tileColorsarray. - Performance: For larger grids, consider memoizing the tile rendering with
React.memoto avoid unnecessary re-renders.
内容的提问来源于stack exchange,提问作者Grafgurke

