简体   繁体   中英

React - looping through values in render() function in JSX

Rookie question, but i'm new to react and i want to loop the value from my state in the render method.

My current (working) code:

render() {
    return (
      <div>
        <div className="status">{status}</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>
    );
  }

And i would love something like:

render() {    
    return (
      <div>
        <div className="status">{status}</div>
        for (var i = 0; i < this.state.squares; i++) {
          if (i!=0 && i % 3 == 0) { 
            <div className="board-row">
          }

          {this.renderSquare(i)}

          if (i!=0 && i % 3 == 0) { 
            </div>
          }
        }
      </div>
    );
  }

Obivously this syntax does not work, but hopefully you get the gist.

The way to loop over in the render function is by using map.

 render() { return ( <div> <div className="status">{status}</div> { this.state.squares.map((square, idx) => idx % 3 === 0 ? <div className="board-row" key={idx}> {this.renderSquare(idx)} // This makes sure no extra elements are created. {this.state.squares[idx + 1] && this.renderSquare(idx + 1)} {this.state.squares[idx + 2] && this.renderSquare(idx + 2)} </div> : null )}} ); } 

Assuming, ReactJS v16.0.0+, you could do something like:

renderSquareWithWrapper(index){
    const inclWrapper = (index != 0 && index%3 ==0);

    return (
      <React.Fragment>
        { inclWrapper 
            ? <div key={index} className="board-row">{ this.renderSquare(index) }</div>
            : this.renderSquare(index)
         }
      </React.Fragment>,
    );
}

render() {    
    return (
      <div>
        <div className="status">{ status }</div>
        { Array.isArray(this.state.squares) 
            && this.state.squares.map( (_, idx) => this.renderSquareWithWrapper(idx) ) }
      </div>
    );
}

Don't forget to ensure you add "key" props to your renderSquare element otherwise you will get a React warning (it's how it identifies -- internally -- each component). The above example leverages Content Fragments which were introduced in ReactJS 16+

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