React - Create nested components with loops

后端 未结 14 1767
情话喂你
情话喂你 2020-12-30 01:27

I have a little issue with React. I can\'t create a nested component with a for loop. What I want to do is create 9 cells of a table and then create 3 rows with 3 cells for

14条回答
  •  無奈伤痛
    2020-12-30 02:04

    My solution is:

    class Board extends React.Component {
    
        //range is a Sequence generator function
        //Array.from(arrayLike[, mapFn [, thisArg]]).
        //arrayLike - An array-like or iterable object to convert to an array
        //mapFn - Map function to call on every element of the array
        //thisArg - Value to use as this when executing mapFn
        //range(0, 4, 1);  => [0, 1, 2, 3, 4] 
    
        range = (start, stop, step) => Array.from(
            { length: (stop - start)/step +1 }, 
            (_, i) => start + (i * step)
        );
    
        renderSquare(i) {
            return  this.props.onClickChange(i)} 
                />;
        }
    
        render() {
        let row = 3;
        let col = 3;
        return (
            
    { //This generates an Array of [0, 3, 6] if row = 3 and col = 3 // n is the element and i is the index of the element, i starts at 0 this.range(0, row * col - 1, col).map( (n, i) => { return (
    { this.range(n, (i + 1) * col - 1, 1).map( (n, i) => { return this.renderSquare(n) }) }
    ) }) }
    ); }

提交回复
热议问题