如何使用嵌套array.map将板上的位置从板发送到React JS中的单元组件



我正在用 React JS 制作一个由 2D 数组表示的游戏板。Board 组件使用 array.map 函数循环访问行,并使用嵌套的 array.map 函数再次对列进行呈现 Cell 组件以形成表。

我不知道如何将电路板/阵列上的位置发送到单元组件。我想在每个嵌套循环中制作带有行号和列号的 2 元素数组,并将其作为道具发送到单元格。

但是如何访问外部映射函数的索引呢?

以下是我的电路板和单元组件:

var Board = React.createClass({
  //dungeon map available in this.props.board  
  render: function() {
    return (
      <table className="table">
        {
          this.props.board.map(function(item,index){
          //loop through every element of the board array
          //these are the rows
          var row = index;
            return (
              <tr>
                {
                  item.map(function(item,index){
                    var position = [row, index]
                    //this does not work for row
                   //row from outer map loop not accessible
                    return (
                      <Cell value={item} position ={position}/>
                    )
                  }.bind(this))

                }
              </tr>  

            )

          }.bind(this))
        } 
      </table>
    )
  }
});
var Cell = React.createClass({
//this.props.position available here
    return (
      <td>
        {this.props.item}
      </td>
    )
  }
});

您需要在绑定中传递它:

var Board = React.createClass({
//dungeon map available in this.props.board  
render: function() {
    return (
    <table className="table">
        {
        this.props.board.map(function(item,index){
        //loop through every element of the board array
        //these are the rows
        var row = index;
            return (
            <tr>
                {
                /** NOTICE rowIndex **/  
                item.map(function(rowIndex, item,index){
                    var position = [row, index]
                    //this does not work for row
                //row from outer map loop not accessible
                    return (
                    <Cell value={item} position ={rowIndex}/>
                    )
                /** NOTICE we pass the row's index to binding **/
                }.bind(this, index))

                }
            </tr>  

            )

        }.bind(this))
        } 
    </table>
    )
}
});

注意:顺序很重要。 注意rowIndex是第一位的。

最新更新