reactjs 表React JS中的递归循环

6uxekuva  于 2023-01-12  发布在  React
关注(0)|答案(1)|浏览(137)

是否可以呈现动态列以及基于列的数据
我尝试在react JS中基于数组呈现动态表列及其数据。

var cols = ["Id", "Name"];
const generateData = () => {
    var testArr = [];
    for (let i = 0; i < 100; i++) {
        testArr.push({ Id: i + 1, Name: names[Math.round(Math.random() * 10)] });
    }
    return testArr;
}

import { Table } from "reactstrap";

function dynamicTables(props) {
    debugger
    return (
        <Table className="align-items-center table-flush" responsive>
            <thead className="thead-light">
                <tr>
                    {
                        props.cols.map((item, key) => (
                            <th key={key}>{item}</th>
                        ))
                    }
                </tr>
            </thead>
            <tbody>
                {
                    props.data.map((item, key) => (
                        <tr key={key}>
                            {
                                props.cols.map((col) => {
                                    <td>{item[col]}</td>
                                })
                            }
                        </tr>
                    ))
                }
            </tbody>
        </Table>
    );
}

export default dynamicTables;

调用组件:

<dynamicTables data={generateData()} cols={cols}></dynamicTables>
6ojccjat

6ojccjat1#

这对我很有效

var cols = ["Id", "Name"];
const generateData = () => {
    var testArr = [];
    for (let i = 0; i < 100; i++) {
        testArr.push({ Id: i + 1, Name: names[Math.round(Math.random() * 10)] });
    }
    return testArr;
}

import { Table } from "reactstrap";

function dynamicTables(props) {
    debugger
    return (
        <Table className="align-items-center table-flush" responsive>
            <thead className="thead-light">
                <tr>
                    {
                        props.cols.map((item, key) => (
                            <th key={key}>{item}</th>
                        ))
                    }
                </tr>
            </thead>
            <tbody>
                {
                    props.data.map((item, key) => (
                        <tr key={key}>
                            {
                                props.cols.map((col) => {
                                    return <td>{item[col]}</td>
                                })
                            }
                        </tr>
                    ))
                }
            </tbody>
        </Table>
    );
}

export default dynamicTables;

相关问题