React - Create nested components with loops

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

    The first solution:

    import React from 'react';
    import Square from './Square';
    
    export default
    class Board extends React.Component {
      render() {
        const board2 = [];
    
        for (let i = 0; i < 3; i++) {
          const s = [];
          for (let k = 0; k < 3; k++) {
            s[k] = this.props.onClick(3*i+k)}
              />;
          }
          board2[i] = 
    {s}
    ; } /////////////////////////////////////// return (
    {board2}
    ); } }

    The second solution:

    import React from 'react';
    import Square from './Square';
    
    export default
    class Board extends React.Component {
      render() {    
        let board   =Array(3).fill(null);
        let square  =Array(3).fill(null);
    
        const x = board.map((b,bIndex)=>{
          return
    { square.map((s, sIndex)=>{ return this.props.onClick(3*bIndex+sIndex)} />; }) }
    ; }); /////////////////////////////////////// return (
    {x}
    ); } }

    Square:

    import React from 'react';
    
    export default
    function Square(props) {
      console.log('square render')
      return (
        
      );
    }
    

提交回复
热议问题