首页 > 解决方案 > ReactJS - 在整个网页上显示一个网格

问题描述

我正在尝试在整个网页上显示一个由具有相等高度/宽度的小单元组成的网格,如下所示的示例,我正在寻找一种方法来做到这一点,因为这是我的第一个反应项目:

在此处输入图像描述

这是 Main.jsx

import React, {Component} from 'react';
import Node from './Node/Node';

import './Main.css';

export default class Main extends Component {
    constructor(props){
        super(props);
        this.state = {
            nodes: [],
        };
    }

    componentDidMount(){
        const nodes = [];
        for(let row = 0; row < 15; row++){
            const currentRow = [];
                for(let col = 0; col < 50; col++){
                currentRow.push([]);
            }
            nodes.push(currentRow);
        }
        this.setState({nodes})
    }

    render(){
        const {nodes} = this.state;
        return(
            <div className="grid">
                {nodes.map((row, rowIndex)=>{
                    return <div>{row.map((node, nodeIndex)=><Node></Node>)}</div>
                })}
            </div>
        );
    }
}

这是 Node.jsx:

import React, {Component} from 'react';

import './Node.css';

export default class Node extends Component {
    constructor(props){
        super(props);
        this.state = {};
    }

    render(){
        return <div className="node"></div>
    }
}

标签: reactjsgridreact-component

解决方案


您应该在其中创建一个html table而不是div,您将需要映射一个 的数组<tr>,该数组由一个 的数组组成<td>

这是一个未编译的逻辑示例:

<table>
    {Array(65).fill(0).map(() =>
        (<tr>
            {Array(65).fill(0).map(() =>
                <td></td>
            )}
        </tr>)
    )}
</table>

这只是为了说明逻辑。您需要根据单元格的宽度以及用户屏幕的总宽度和高度来计算数字 65。


推荐阅读