如何在 React 中正确绑定 onClick 事件以避免类型错误

React 中 onClick 期望接收一个函数,若传入字符串或直接执行表达式(如 window.href='...')会导致"Expected onclick listener to be a function"报错;正确做法是使用箭头函数包裹逻辑。 react 中 `onclick` 期望接收一个函数,若传入字符串或直接执行表达式(如 `window.href='...'`)会导致"expected `onclick` listener to be a function"报错;正确做法是使用箭头函数包裹逻辑。在 React 中,事件处理器(如 onClick)必须是函数类型------这是 JSX 渲染机制的强制要求。当你这样写:<button onClick={window.href='https://github.com/'} className="btn btn-github"> Visit GitHub</button>React 实际上会在组件渲染时立即执行 window.href='https://github.com/'(注意:此处应为 window.location.href,window.href 并不存在),并将赋值结果(即字符串 'https://github.com/')作为 onClick 的值传入。这违反了 React 的事件处理规范,因此抛出错误:Expected onclick listener to be a function, instead got a value of string type.? 正确写法是将事件逻辑封装为一个函数,并通过箭头函数(或具名函数)传递给 onClick: Cleanup.pictures 智能移除图片中的物体、文本、污迹、人物或任何不想要的东西

相关推荐
金銀銅鐵9 分钟前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup115 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi007 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵9 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf9 小时前
Agent 流程编排
后端·python·agent
copyer_xyf10 小时前
Agent RAG
后端·python·agent
copyer_xyf10 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf10 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python