简体   繁体   中英

How to create loop inside React return?

I just learn React so i have a question. I develop the Tic-toe game which is stayed in the official documentation. There are extra-tasks bellow the "Tutorial". One of them is

"Rewrite Board to use two loops to make the squares instead of hardcoding them."

We have this code for generation playing field:

 return (
  
  <div>
    <div className="board-row">
      {this.renderSquare(0)}
      {this.renderSquare(1)}
      {this.renderSquare(2)}
    </div>
    <div className="board-row">
      {this.renderSquare(3)}
      {this.renderSquare(4)}
      {this.renderSquare(5)}
    </div>
    <div className="board-row">
      {this.renderSquare(6)}
      {this.renderSquare(7)}
      {this.renderSquare(8)}
    </div>
  </div>
);

But we should remake this using any loop. I started to search information about this but found solution only with using map. So now i have code like this:

const mas = Array(3).fill(null)

let i = -1;
return(
    <div>
      {mas.map(() =>{
        return(
        <div className = "board-row">
            {mas.map(() => {
                i+= 1;
                return (<span key={i}>{this.renderSquare(i)}</span>);
            })}
        </div>)
      })}
    </div>
)

Probably there is another solution of this task... Using for example for loop or something like this...

This is absolutely fine, but another option would be exporting the rows to their own component, this way you would be able to return the following:

{[1,2,3].map((key) => <Row key={key} />)}

And the row component could return the following

{[1,2,3].map((key) => <span key={key}>renderSquare(key)</span>)}
    const renderItems = [
    {
        id: 0
    },
    {
        id: 1
    },
    {
        id: 2
    },
    {
        id: 3
    },
    {
        id: 4
    },
    {
        id: 5
    },
    {
        id: 6
    },
    {
        id: 7
    },
    {
        id: 8
    },
    {
        id: 9
    }
];

const Board = ({ itemNo }) => {
    return <p>{itemNo}</p>;
};

const BoardGame = () => {
    return (
        <div className='grid cols-3'>
            {renderItems.map(item => {
                return <Board key={item?.id} itemNo={item?.id} />;
            })}
        </div>
    );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM