如何使用react显示两列或更多列中的地图结果

Nes*_*zin 8 javascript jsx typescript reactjs

我想我有一个简单的问题,但我无法通过反应得到解决方案,我希望在两列中显示结果:

item 1 | item 4
item 2 | item 5
item 3 | item 6
Run Code Online (Sandbox Code Playgroud)

我试过验证数组lenght是0还是新的起始列,但是我不能绘制一个start div元素而不绘制end div元素

我想做这样的事情:

render() {

        const secondColumnStart = this.props.result.length / 2;

        return <div className="row">
                {this.props.result.map((item, i) => 
                { (i == 0 || i == secondColumnStart) && <div className="col-md-6"> }
                    item.value
                { (i == 0 || i == secondColumnStart) && </div> })}
            </div>;
    }
Run Code Online (Sandbox Code Playgroud)

Fuz*_*ree 7

如果您总是想要恰好两列,那么一种选择是调用map两次。对数组的每一半进行一次:

const secondColumnStart = Math.floor(this.props.result.length / 2);

return (
    <div className="row">
        <div className="col-md-6">
            {this.props.result.slice(0,secondColumnStart).map(item => item.value)}
        </div>
        <div className="col-md-6">
            {this.props.result.slice(secondColumnStart).map(item => item.value)}                
        </div>
    </div>
);
Run Code Online (Sandbox Code Playgroud)


RIY*_*HAN 7

假设有两列,具有col-md-6用于行拆分的类。

创建无状态组件 myRow

const myRow = ({index})=>{(<div className="col-md-6">{index}</div>)}
Run Code Online (Sandbox Code Playgroud)

为每个列创建数组

const col1 = [],col2 = [];

this.props.result.forEach((item, i) => {
    if(i%===0){
        col1.push(myRow);
    }else{
        col2.push(myRow);
    }
}
Run Code Online (Sandbox Code Playgroud)

返回render中的React元素。

return <div className="row">
                {col1}{col2}
            </div>;
Run Code Online (Sandbox Code Playgroud)


Bil*_*khi 7

只需像平时从一个数组中那样映射项。这样,使用CSS属性“列”显示它们,如上面的问题所述。

.container {
  columns: 2 auto;
}
Run Code Online (Sandbox Code Playgroud)