javascript - 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>
);
解决方案
大多数事件处理程序只接受事件对象作为它们的参数。但这并不意味着您不能将其他内容传递给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>
)
工作代码沙盒
推荐阅读
- vlookup - 用于 VLOOKUP 和 SUMIF 公式的虚拟数组
- java - 通过 JavaWeb 在整个 MySQL 数据库中搜索关键字的推荐方法
- python - 服务器发送速度比客户端接收速度快
- jitpack - JitPack 构建失败并出现错误:获取容器状态超时
- solidity - Solidity 导入多个声明
- vue.js - Vue中的计算函数未定义
- javascript - 无法使用 AJAX 将数组从 JS 传递到 PHP
- javascript - 如何为 paypal api 显示 javascript 对象?
- java - 为什么我们需要注解“RequestParam()”
- reactjs - 如何防止在更新某些 Firestore 文档时重新加载整个组件?