轻松学会React:左侧树形结构+右侧表格的完整代码示例教学

在React中实现左侧树形结构加右侧表格的布局是一个常见的需求,它能够有效地展示和操作大量数据。下面,我将带你一步步通过一个完整的代码示例来学习如何实现这样的布局。
环境准备
在开始之前,请确保你的开发环境已经安装了以下工具:
Node.js
npm 或 yarn
React
Create React App(用于快速搭建项目)
你可以使用以下命令来创建一个新的React项目:
npx create-react-app tree-table-app
cd tree-table-app
项目结构
我们的项目结构将如下所示:
tree-table-app/
├── public/
│ └── index.html
├── src/
│ ├── components/
│ │ ├── Tree.js
│ │ └── Table.js
│ ├── App.js
│ ├── index.js
│ └── index.css
├── package.json
└── README.md
Tree.js 组件
首先,我们创建一个
Tree.js
组件来展示树形结构。
// src/components/Tree.js
import React from ‘react’;

const Tree = ({ data }) => {
const renderTree = (data) => {
return data.map((item) => (

  • {item.name}
    {item.children &&

      {renderTree(item.children)}

    }

  • ));
    };

    return

      {renderTree(data)}

    ;
    };

    export default Tree;
    Table.js 组件
    接下来,我们创建一个
    Table.js
    组件来展示表格数据。
    // src/components/Table.js
    import React from ‘react’;

    const Table = ({ data }) => {
    return (

    {data.map((item) => (

    ))}

    ID Name Age
    {item.id} {item.name} {item.age}

    );
    };

    export default Table;
    App.js 组件
    现在,我们将这些组件组合到
    App.js
    中。
    // src/App.js
    import React from ‘react’;
    import Tree from ‘./components/Tree’;
    import Table from ‘./components/Table’;
    import ‘./index.css’;

    const App = () => {
    const treeData = [
    {
    id: 1,
    name: ‘Node 1’,
    children: [
    { id: 2, name: ‘Node 1.1’ },
    { id: 3, name: ‘Node 1.2’ },
    ],
    },
    {
    id: 4,
    name: ‘Node 2’,
    },
    ];

    const tableData = [
    { id: 1, name: ‘Alice’, age: 25 },
    { id: 2, name: ‘Bob’, age: 30 },
    { id: 3, name: ‘Charlie’, age: 35 },
    ];

    return (

    );
    };

    export default App;
    样式(index.css)
    最后,我们添加一些基本的样式。
    /* src/index.css */
    .container {
    display: flex;
    height: 100vh;
    }

    .tree-container,
    .table-container {
    flex: 1;
    padding: 20px;
    }

    table {
    width: 100%;
    border-collapse: collapse;
    }

    th,
    td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
    }

    th {
    background-color: #f2f2f2;
    }
    运行项目
    现在,你可以启动你的React应用来查看效果:
    npm start
    当你访问
    http://localhost:3000
    时,你应该能看到一个左侧的树形结构和一个右侧的表格。
    通过这个例子,你不仅学会了如何在React中实现左侧树形结构加右侧表格的布局,还了解了如何将不同的组件组合在一起来构建复杂的用户界面。希望这个教程能帮助你更好地掌握React!