jsx loop wrapper for html component on condition

柔情痞子 提交于 2019-12-25 12:53:51

问题


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.

here's the code:

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')
);

here's a JSFIDDLE

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

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>

what I have:

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

回答1:


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.

Here's the render function:

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>
    );
}


来源:https://stackoverflow.com/questions/33856949/jsx-loop-wrapper-for-html-component-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!