Create html structure which will allow only 3 div

2019-07-16 15:07发布

问题:

This is bit copy of How to create html structure which will allow only 3 div elements in each li. In React + underscore.js

Actually i am facing issue while iterating array in li.

I have below array structure

 var xyz = [{'name': ['abc','xyz','test','test1','test2','test3','test4'] }];

and i want below output structure

<ul>
<li>
   <div><span>test3</span></div>
   <div><span>test4</span></div>
   <div><span>test5</span></div>
</li>
<li>
   <div><span>test6</span></div>
   <div><span>test7</span></div>
   <div><span>test8</span></div>
</li>


I am using React and underscore.js on my project. I want everything in pure react function I tried to append li's into ul as a string but that is bad practice it react.js Can anyone help me in this.

Using below function i have created array structure which will contain 3 values in one array object.

    var n = 3;
    var chunkedlists = _.chain(this.state.serialIdFilter).groupBy(function(element, index){
        return Math.floor(index/n);
    }).toArray().value();

Now i want help in printing this into proper structure as i mentioned using react + underscore.js.

回答1:

const Com = () => {
    var xyz = [{'name': ['abc','xyz','test','test1','test2','test3','test4'] }];

    return (
        <ul>
            {_.map(_.chunk(xyz[0].name, 3), (innerItem, i) => (
                <li key={i}>
                    {_.map(innerItem, (name, j) => (<div key={j}><span>{name}</span></div>))}
                </li>
            ))}
        </ul>
    );

}

ReactDOM.render(<Com />, document.getElementById("container"));

An example bin an be found here: http://jsbin.com/menidu/4/edit?js,output



回答2:

something like this would be required

return ( <ul>{chunkedLists.map(group => <li>{group.map(i => <div><span>{i}</span></div>)}</ul>)} )