React - Create nested components with loops

后端 未结 14 1814
情话喂你
情话喂你 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:17

    Live demo on codepen

    Nested loops in render() function (explanation in comments:)

    class Board extends React.Component {
      renderSquare(i) {
        return (
           this.props.onClick(i)}
          />
        );
      }
    
      render() {
         var self = this;
        return (
          
    // you can use: [...Array(3)] instead of [1,2,3] {[1, 2, 3].map(function(row, rowIdx) { // create rows return (
    { // you can use: [...Array(3)] instead of [1,2,3] [1, 2, 3].map((col, colIdx) => { // create columns return self.renderSquare((3 * rowIdx) + colIdx); // calculate square index }) }
    ); })}
    ); } }

提交回复
热议问题