react中onclick_在React js中调试onclick事件的问题

react中onclick

A handleClick event wasn’t behaving like I expected it to behave. I replaced everything inside it with a console.log to make it easier to tell what was going on.

handleClick事件的行为不像我预期的那样。 我用console.log替换了其中的所有内容,以便更轻松地知道发生了什么。

When the component loaded, the event fired many times.

加载组件后,该事件将触发多次。

Image for post
💩💩💩💩💩💩💩💩💩
💩💩💩💩💩💩💩💩💩

This indicated to me that the function was being run many times when the component was loaded.

这向我表明该函数在加载组件时正在运行多次。

If the function was not running at all, I would have put thiss on things until it worked. Because it was running too many times, I removed () s until it worked.

如果函数不是在所有运行,我将不得不把this S于事,直到它的工作。 因为它运行了太多次,所以我删除了()直到起作用。

Image for post

Now it only poop s when I click on the div. Success.

现在,只有当我单击div时,它才会poop 。 成功。

Image for post
💩🎉
💩🎉

What are your best tips and tricks for debugging React?

您调试React的最佳秘诀是什么?

翻译自: https://medium.com/@merxplat/debugging-a-problem-with-an-onclick-event-in-react-js-8096d6c28c8c

react中onclick

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要从表格外部的`onClick`事件获取当前表格的所有数据,可以采用以下步骤: 1. 在表格组件,创建一个`ref`引用,用于获取表格的DOM节点: ```jsx import React, { useRef } from "react"; function Table() { const tableRef = useRef(null); return ( <table ref={tableRef}> {/* 表格内容 */} </table> ); } ``` 2. 在点击事件处理函数,通过`tableRef.current`获取表格DOM节点,再通过`querySelectorAll`方法获取所有的`<tr>`元素: ```jsx function handleClick() { const rows = tableRef.current.querySelectorAll("tr"); console.log(rows); } function Table() { const tableRef = useRef(null); return ( <div> <button onClick={handleClick}>获取表格数据</button> <table ref={tableRef}> {/* 表格内容 */} </table> </div> ); } ``` 3. 遍历`<tr>`元素,获取每行的数据: ```jsx function handleClick() { const rows = tableRef.current.querySelectorAll("tr"); const data = []; rows.forEach((row) => { const rowData = []; row.querySelectorAll("td").forEach((cell) => { rowData.push(cell.textContent); }); data.push(rowData); }); console.log(data); } ``` 完整代码如下: ```jsx import React, { useRef } from "react"; function Table() { const tableRef = useRef(null); function handleClick() { const rows = tableRef.current.querySelectorAll("tr"); const data = []; rows.forEach((row) => { const rowData = []; row.querySelectorAll("td").forEach((cell) => { rowData.push(cell.textContent); }); data.push(rowData); }); console.log(data); } return ( <div> <button onClick={handleClick}>获取表格数据</button> <table ref={tableRef}> <thead> <tr> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody> <tr> <td>张三</td> <td>20</td> </tr> <tr> <td>李四</td> <td>25</td> </tr> </tbody> </table> </div> ); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值