微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将函数参数作为参数传递并将参数传递给该函数?

如何解决将函数参数作为参数传递并将参数传递给该函数?

所以我目前正在用 React javascript 编写一个 3D 国际象棋游戏。我有一个游戏类、一个棋盘类和一个瓷砖类。游戏类包含所有的板,我希望它是我的 handleClick 方法所在的位置。 board 类是一个二维的 Tiles 数组,而 Tile 类基本上只是一个彩色按钮。

句柄点击方法需要访问tile的x和y坐标,我可以从board类中获取,但是我希望该方法激活tile类中按钮的onClick。

我想将 handleClick 方法从游戏传递到棋盘,跟踪指标,并获取要在 Tile 的 onClick 中调用函数

class Tile {
  render(onClick) {
    return (
      <button 
        onClick={onClick}
      />);
  }
}


class Board {
  constructor() {
    this.state = {tiles: 
      [[new Tile(),new Tile(),new Tile()],[new Tile(),new Tile()]]
    }
  }

  // loops through all rows and calls render row and returns
  render_board = (onClick) => {
    const board = [];
    for (var i = 0; i < board_stats.height; i++) { 
      board.push(this.render_row(i,onClick));
    } 
    return board;
  }

  // loops through all tiles in row and calls render tile
  render_row = (i,onClick) => {
    const row = [];
    for (var j = 0; j < board_stats.width; j++) {
      row.push(this.render_square(i,j,onClick));
    }
    return <div className="board-row"> {row} </div>
  }


  render_tile(i,onClick) {
    return <Square
      onClick=/*I want to send the onClick method to the square with the parameters i and j*/
    />;
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      board: new Board()
    };
  }

  handle_click = (i,j) => {
    // Do Stuff
  }

  render() {
    return (
      <div className="game">
        <div className="game-board">
          {this.state.board.render_board(/*I want to send the handle click method here*/)}
        </div>
      </div>
    );
  }
}

我已经简化了代码,以便于阅读。

我不知道该怎么做。我认为可能有一种方法可以用粗箭头符号来做到这一点,但我不确定如何。任何帮助将不胜感激

解决方法

要解决您的问题,请执行以下操作:

// In Board class
  render_tile(i,j,onClick) {
    return <Square
      onClick={() => onClick(i,j)}
    />;
  }

您可以将 render_board(onClick) 方法重命名为 render({onClick}),以允许写入
<Board onClick={handle_click} /> 而不是
{this.state.board.render_board(/*I want to send the handle click method here*/)}
这样你就可以更像设计的那样使用 React。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?