React按钮组件onClick事件传递报错,如何正确传参解决类型问题?
解决React按钮事件传递的类型错误问题
兄弟,咱们先扒一扒你代码里的问题根源:
你现在在onClick属性里直接写了submitButton(event, props)——这会导致组件一渲染就立刻执行这个函数,完全不是点击按钮时才触发的逻辑!而且此时event变量根本没定义,自然会出现类型不匹配的报错。另外还有个小隐患:onClick是可选属性,直接调用props.onClick(event)如果用户没传这个属性,会直接抛出错误。
下面给你两种靠谱的修正方案,选哪个都能解决问题:
方案一:箭头函数包裹(简单直接)
用箭头函数把事件和props包起来,这样只有点击按钮时才会触发submitButton:
import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: React.MouseEvent<HTMLButtonElement>): void; type?: string; } const submitButton = (event: React.MouseEvent<HTMLButtonElement>, props: Props) => { event.preventDefault(); // 用可选链判断onClick是否存在,避免无此属性时报错 props.onClick?.(event); }; export const ButtonComponent = (props: Props) => { return ( <button className={props.className} type={props.type || 'button'} // 给type加默认值,避免form里意外提交 onClick={(event) => submitButton(event, props)} > {props.text} </button> ); };
方案二:让submitButton返回事件处理函数(性能更优)
这种写法不会每次组件渲染都创建新的箭头函数,适合需要优化性能的高频渲染场景:
import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: React.MouseEvent<HTMLButtonElement>): void; type?: string; } // 先接收props,再返回一个处理事件的函数 const submitButton = (props: Props) => (event: React.MouseEvent<HTMLButtonElement>) => { event.preventDefault(); props.onClick?.(event); }; export const ButtonComponent = (props: Props) => { return ( <button className={props.className} type={props.type || 'button'} onClick={submitButton(props)} // 直接传函数引用,点击时触发 > {props.text} </button> ); };
额外补充个小细节:给type加了|| 'button'的默认值,因为button标签的默认type是submit,如果放在form标签里可能会意外触发表单提交,加个默认值更稳妥。
内容的提问来源于stack exchange,提问作者Gerard López Sorribas
相关产品推荐
相关产品推荐

