繁体   English   中英

React-遍历JSX中render()函数中的值

[英]React - looping through values in render() function in JSX

新秀问题,但我是新来的人,我想在render方法中从状态中循环值。

我当前的(工作)代码:

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>
    );
  }

我会喜欢这样的:

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>
    );
  }

显然,这种语法不起作用,但是希望您能理解。

渲染功能中的循环方法是使用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 )}} ); } 

假设ReactJS v16.0.0 +,您可以执行以下操作:

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>
    );
}

不要忘记确保将“关键”道具添加到renderSquare元素中,否则您将收到React警告(这是它在内部标识每个组件的方式)。 上面的示例利用了ReactJS 16+中引入的Content Fragments

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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