代码之家  ›  专栏  ›  技术社区  ›  Shishir Karki

在react(typescript)项目上未渲染图像

  •  0
  • Shishir Karki  · 技术社区  · 1 年前

    我正在做一个项目,使用react构建一个简单的棋盘UI进行练习。我遇到了一个问题,无法在特定的图块上渲染给定的块。有人能帮我找出潜在的问题所在吗?我已确保图像路径正确。它位于公用文件夹内的images文件夹中。

    PS:我是初学者,我知道的不多。

    //Typescript for react component
    
    import './chessboard.css';
    import Tile from "../Tiles/tile";
    
    
    interface piece {
        image?: string;
        x: number;
        y: number;
    }
    
    const pieces: piece[] = [];
    const horizontalAxis = ["a", "b", "c", "d", "e", "f", "g", "h"];
    const verticalAxis = [1, 2, 3, 4, 5, 6, 7, 8];
    
    
    pieces.push({ image: "/images/black_pawn.png", x: 0, y: 1 });
    
    export default function Chessboard() {
        let board = [];
    
        for (let j = verticalAxis.length - 1; j >= 0; j--) {
            for (let i = 0; i < horizontalAxis.length; i++) {
                const number = i + j + 2;
                let image = undefined;
    
                pieces.forEach(p => {
                    if (p.x === i && p.y === j) {
                        image = p.image;
                    }
                });
                
                board.push(<Tile  image={image} number={number} />);
            }
        }
    
        
    
        return <div id="chessboard">{board}</div>;
    }
    
    
    
    
    
    //TypeScript for tile component
    
    import './tile.css';
    
    
    interface props{
        image?: string;
        number: number;
    }
    
    export default function Tile({image, number}: props){
        if(number%2===0){
            return (<div className="tile black-tile"></div>)
        }else{
            return (<div className="tile white-tile"></div>)
        }
    }
    
    1 回复  |  直到 1 年前
        1
  •  0
  •   Harsh Shah    1 年前

    看起来问题出在Tile组件上,你实际上并没有使用传递的图像道具。要在图块上渲染棋子,您需要修改图块组件以显示图像(如果存在)。

    已更新 Tile 组件( tile.tsx )

    import './tile.css';
    
    interface props {
        image?: string;
        number: number;
    }
    
    export default function Tile({ image, number }: props) {
        const tileClass = number % 2 === 0 ? "tile black-tile" : "tile white-tile";
    
        return (
            <div className={tileClass}>
                {image && <img src={image} alt="chess piece" className="piece-image" />}
            </div>
        );
    }
    

    更新CSS( tile.css )

    .piece-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
    }