首页 > 解决方案 > React onMouseDown:将事件与参数一起传递

问题描述

我正在尝试将一个事件与其他两个参数一起传递给 handleOnMouseDown 函数。我现在的代码如下所示: onMouseDown={(e) => {this.handleMouseDown(e,row,col)}}

在我的 handleMouseDown 函数中,我有:

handleMouseDown = (event,row,col) => {
    event.preventDefault();
    ...
}

但是,当我调用“.preventDefault”函数时出现错误。错误说:

TypeError:event.preventDefault 不是函数

为什么会这样?

编辑(提供更多上下文):在我的渲染函数中,我正在生成一个由节点组成的网格,每个节点都有一个特定的列号和行号。我在渲染中的代码片段如下所示:

         {this.state.grid.map((row, rowIdx) => {
              return (
                <div key={rowIdx}>
                  {row.map((node, nodeIdx) => {
                    const {
                      row, 
                      col
                    } = node;
                    return (
                      <Node
                        key={nodeIdx}
                        col={col}
                        onMouseDown={(row,col,event) => {this.handleMouseDown(row,col,event)}}
                        row={row}></Node>
                    );
                  })}

在每个节点中,我在我的渲染函数中调用 onMouseDown,如下所示:

          return (
            <div onMouseDown={() => onMouseDown(row, col)}>
            </div>
          );

标签: javascriptreactjs

解决方案


大多数事件处理程序只接受事件对象作为它们的参数。但这并不意味着您不能将其他内容传递给handleMouseDown回调函数。你会想这样写:

handleMouseDown = (e, row, col) => {

   e.persist()
   e.preventDefault()

   console.log(e, row, col)
   // whatever you'd like to do with e, row, and col

}

// Inside your render:

const row = 'whatever'
const col = 'and stuff'

return (
  <button onMouseDown={(e) => {this.handleMouseDown(e,row,col)}}>
    This will work
  </button>
)

工作代码沙盒


推荐阅读