React:在数组中为每个项创建一行

时间:2018-02-14 12:39:37

标签: javascript html reactjs jsx

我将一个对象数组作为prop组件传递给我的Table组件,它应该将数组中的每个项目都转换为表格中的一行。但它没有输出任何东西......

我已使用console.log成功查看数组中的每个项目。这是我的代码:

import React from 'react'; 

export default class Table extends React.Component {
    getTableRow(x) {
        console.log(x); 
        return ( <tr>
                <td>{x.prop1}</td>
                <td>{x.prop2}</td>
                <td>{x.prop3}</td>
        </tr>); 
    }

    resolveInput() {
        //expecting array
        const array = this.props.lastFiveList; 
        //array.map(x => console.log(x)); 
        array.map(x => this.getTableRow(x)); 
    }           

    render() {
        return (
            <table>
             {this.resolveInput()}
            </table>
        ); 
    }
}

我还尝试绑定两个函数(相同的结果)并将getTableRow应该返回到变量中,然后返回变量而不是多行return();语句。此外,我尝试使用forEach代替map

3 个答案:

答案 0 :(得分:3)

您未在resolveInput()中返回数组:

    return array.map(x => this.getTableRow(x));

答案 1 :(得分:3)

resolveInput方法没有返回任何内容。你需要返回

resolveInput() {
    //expecting array
    const array = this.props.lastFiveList; 
    //array.map(x => console.log(x)); 
    return  array.map(x => this.getTableRow(x)); 


} 

答案 2 :(得分:0)

您的resolveInput()方法不会返回您从地图创建的数组或返回任何内容。 因此,请尝试返回从传入的数组中映射的新数组。