条件条件下html组件的jsx循环包装器 [英] jsx loop wrapper for html component on condition

查看:84
本文介绍了条件条件下html组件的jsx循环包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用div包装一个ReactJS组件,但是我只想每5个项目包装一个元素.我已经设法(在很少的帮助下)每隔5个项目添加换行符.

I want to wrap a ReactJS component with div, but I want to wrap the elemnt every 5 items only. I've managed (with little help) to add line break every 5 items.

这是代码:

var Item = React.createClass({
    render: function() {
        return <span> {this.props.num}</span>;
    }
});

var Hello = React.createClass({
    render: function() {
        var items = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ];

        return <div>{items.map(function (i,index) {
            if (index % 5 === 0) {
                return [ <br />, <Item key={i} num={i} /> ];
            }

            return <Item key={i} num={i} />;
        })}</div>;
    }
});

ReactDOM.render(
    <Hello name="World" />,
    document.getElementById('container')
);

这是一个 JSFIDDLE

我仍然想使用.map函数遍历数组,这更加方便直观.

i still want to use the .map function to loop through the array, it is more convenient and intuitive.

问题是如何用<div>而不是每5行用<br>包裹它?

the question is how do I wrap it with a <div> and not <br> every 5 lines?

很抱歉给您带来混乱的解释: 想要

sorry for the confusion here is an explanation: wanted:

<div>0 1 2 3 4</div>
<div>5 6 7 8 9</div>

我有什么:

0 1 2 3 4 <br />
5 6 7 8 9 <br />

推荐答案

查看此JSFiddle.将输入数组分为五个批次,并将每个批次包装在div中.这些div(每个都有五个Item子元素)都包裹在另一个div中,该divreturn版本.

Check out this JSFiddle. It breaks the input array into batches of five and wraps each of these batches in a div. These divs--each having five Item components as children--are all wrapped in another div, which is returned.

这是render函数:

render: function() {
    var items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ];
    var fives = [];
    while(items.length) {
        fives.push(items.splice(0, 5));
    }
    return (
        <div>
            {fives.map(function (five, index) {
                return (
                    <div key={index}>
                        {five.map(function (item, index) {
                            return (<Item key={index} num={item} />);
                        })}
                    </div>
                );
            })}
        </div>
    );
}

这篇关于条件条件下html组件的jsx循环包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆