【问题标题】:How do I dynamically add an array to a react-bootstrap table?如何动态地将数组添加到 react-bootstrap 表中?
【发布时间】:2017-09-01 04:00:08
【问题描述】:

我有一个 React 组件,它将根据来自 Ajax 调用的数据呈现一个表。可能只有一行数据,也可能最多有 N 行(不是很大,但有限制)。

使用react-bootstrap,我将如何根据从this.state.data 获得的数据创建表?

这是来自班级render 的一些示例代码。如何根据数组的长度填充各个单元格?

该数组包含我希望填充的每一行的对象,数据对应于NameAddress 以及Age(只是一个示例)。如何用正确的数量填充<td>?它可能是从 1 到 N 的任何位置。

render : function () {


        let personArray = []; // Array containing objects that each match the three columns I wish to populate. 


        for(let i = 0; i < personArray.length; i++){
            console.log(personArray[i]); // Prints correctly each object with three value key pairs inside
        }

        const popoverLeft = (

            <Popover id="popover-positioned-left" title="Country name">
                <Table striped bordered condensed hover>
                    <thead>
                    <tr>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Age</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        // Goes on .. 
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        // Goes on .. 
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        // Goes on .. 
                    </tr>
                    </tbody>
                </Table>
            </Popover>
        );

        return(
            <div>
                <OverlayTrigger trigger="click" placement="right" overlay={popoverLeft}>
                    <div>
                    </div>
                </OverlayTrigger>
            </div>
        )

【问题讨论】:

    标签: javascript arrays reactjs react-bootstrap


    【解决方案1】:

    你可以这样做:

    在你的渲染中:

    <Table striped condensed hover>
      <thead>
        <tr>
          <th></th>
          <th>Name</th>
          <th>Address</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        {personArray.map(this.renderPerson)}
      </tbody>
    </Table>
    

    你的 renderPerson 函数:

    renderPerson(person, index) {
      return (
        <tr key={index}>
          <td>{person.name}</td>
          <td>{person.address}</td>
          <td>{person.age}</td>
        </tr>
      )
    }
    

    map 函数将遍历您的数组并返回要渲染的新元素数组。

    【讨论】:

    • 谢谢,试试这个。不过,在您的示例中,renderPerson 不应该是 function renderPerson 吗?
    • 我是用 ES6 语法写的,所以你是对的,你必须根据你的语法需要调整它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2020-04-29
    • 2020-05-02
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多