【问题标题】:Dynamic <table> not rendering data动态 <table> 不呈现数据
【发布时间】:2020-02-10 20:18:27
【问题描述】:

我正在尝试创建一个动态表,该表根据

的格式呈现插入的数据
{headers: ["header1", "header2"], rows: [["data1", "data2"], ["moredata", "wowoso muchdata"]]}

Rows 只是一个数组数组,每个数组都是表中的一行。

我将这些数据传递给渲染表格的 React 组件。代码如下:

export default class StandardTable extends React.Component<Props, State>{
    constructor(props){
        super(props);

        this.state = {
            tableData: this.props.data
        }
    }

    render(){
        return(
            <div>
            <table id="StandardTable">
                <tbody>
                {this.state.tableData.headers.map(function(header){
                    <th>{header}</th>
                })}
                </tbody>
                <tbody>
                {this.state.tableData.rows.map(function(row){
                    <tr>
                        {row.map(function(rowItem){
                            <td>{rowItem}</td>
                        })}
                    </tr>

                })}
                </tbody>
            </table>
                <style jsx>
                    {`
                    #StandardTable{
                        border: 1px solid black;
                    }`}
                </style>
            </div>
        );
    }




}

我能够控制台记录数据对象并且所有数据都在那里。它还遍历地图函数中的数据,因为我可以在控制台中检查,但不幸的是,该表在实践中显示为空白。

【问题讨论】:

    标签: html reactjs jsx


    【解决方案1】:

    你可以试试这个,不需要返回,你可以使用箭头功能

            <table id="StandardTable">
                <tbody>
                {this.state.tableData.headers.map((header) => (
                    <th>{header}</th>
                ))}
                </tbody>
                <tbody>
                {this.state.tableData.rows.map((row)=>(
                    <tr>
                        {row.map((rowItem)=>(
                            <td>{rowItem}</td>
                        ))}
                    </tr>
    
                ))}
                </tbody>
            </table>
    

    希望它会起作用。

    【讨论】:

    • 不是第一个可行的解决方案,但使它成为最好的解决方案,因为使用箭头函数比投入回报更好。谢谢!
    【解决方案2】:

    这是因为您忘记了return。只需在您的地图函数中执行此操作:

                {this.state.tableData.headers.map(function(header){
                    return <th>{header}</th>
                })}
    

    【讨论】:

      【解决方案3】:

      map 中没有return

      this.state.tableData.rows.map(function(row){
                         return( <tr>
                              {row.map(function(rowItem){
                                 return <td>{rowItem}</td>
                              })}
                          </tr>)
      
                      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多