将rect组件数组映射为两个元素的组

时间:2017-12-08 04:13:48

标签: javascript reactjs jsx

我有一系列文字输入,比如

var A = [<TextInput ... />, <TextInput ... />, ....]

我希望将这些元素组映射到一行中的两个元素。 也就是说,<TextInput />内包含的每两个<Row>如何实现这一点。 我想要这样的输出

<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
....
....

我在循环中尝试了这段代码但是产生了错误。

{index % 2 === 0 && <Row> }
      <TextInput {...props} />
{index % 2 === 1 ? </Row>}

我认为我们不能仅在jsx

内返回</Row>的结束标记

4 个答案:

答案 0 :(得分:1)

这样的事情应该有效。可能有错误,我还没有测试过这个

<div> 
  {
    A.map((_, index) => 
      (index % 2 === 0) && 
      <Row> 
       {A[index]} 
       {A[index+1] ? A[index+1] : <div />} 
      </Row>
    )
  }
</div>

答案 1 :(得分:1)

var A = [ < TextInput .../>, <TextInput ... / >,...]

    let arrTwoComp = [],
        arrComp = [];
    A.forEach((oneComp, key) => {

        arrTwoComp.push(oneComp);

        if ((key + 1) % 2 === 0) {
            arrComp.push(
                <Row>{arrTwoComp}</Row>
            );
            arrTwoComp = [];
        }
    })


    //display arrComp

    <div>{arrComp}</div>

答案 2 :(得分:1)

类似这样的事情

render() {
  var temp = [], arr = []
  while(A.length){
    temp.push(A.shift())
    A.length && temp.push(A.shift())
    arr.push(temp)
    temp = []
  } // creates array of arrays
  return arr.map(rowOfTwo => 
    <Row>
     {rowOfTwo[0]}
     {rowOfTwo.length > 1 && rowOfTwo[1]}
    </Row>
  )
}

基本上预先形成你的分裂:)

答案 3 :(得分:1)

const A = [<TextInput ... />, <TextInput ... />, ....];
A.map((_, idx) => {
  if (idx % 2 === 0) {                // only do this on 0 and even indexs
    let inputs = [A[idx]];            // we'll always have an item at idx
    const y = A[idx+1];               // but idx+1 may not exist (i.e., idx was the last item)
    if (y) {                          // if idx+1 doesn't exist, it'll be undefined, so let's avoid including it
      inputs.push(y);
    }
    return (
      <Row>                           // return the items (or item) wrapped in a row
        {...inputs}
      </Row>
    );
  }
}).filter(x => x !== undefined);      // map function has to return something, so the odd indexes will return undefined; lets filter them out now

通过控制台记录显示功能的simple fiddle