TypeScript中React按钮onClick赋值null报错,求类型修复方案
修复React TypeScript按钮组件的onClick类型错误
错误原因
React原生按钮的onClick属性类型为MouseEventHandler<HTMLButtonElement> | undefined,你的代码返回了null,而null不在允许的类型范围内,导致TypeScript类型校验失败。
修复方案
1. 修正onClick属性值
React允许onClick接收undefined,无需用三元表达式返回null,直接传递props.onClick即可,React会自动处理未传入该属性的情况。同时可以去掉多余的函数包装(() => props.onClick()),直接传递原函数即可。
2. 优化Props类型定义
摒弃any | null | undefined的松散类型,改用TypeScript强类型定义,推荐继承React原生按钮的属性类型,让组件支持所有原生按钮特性(如disabled、type等)。
3. 修正PropTypes挂载位置
将Button.prototype改为Button.propTypes,PropTypes需要挂载在组件的propTypes属性上,而非原型链的prototype。
完整修正代码
import React from 'react'; import PropTypes from 'prop-types'; import './button.scss'; // 继承原生按钮属性,同时支持自定义扩展 interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {} const Button = ({ className, onClick, children, ...rest }: ButtonProps) => { return ( <button className={`btn ${className || ''}`} onClick={onClick} {...rest} // 传递其他原生按钮属性 > {children} </button> ); }; export const OutlineButton = (props: ButtonProps) => { return ( <Button className={`btn-outline ${props.className || ''}`} onClick={props.onClick} {...props} > {props.children} </Button> ); }; // 正确挂载PropTypes Button.propTypes = { onClick: PropTypes.func, }; export default Button;
可选精简类型定义
如果不需要原生按钮的全部属性,也可以自定义更精简的Props接口:
interface ButtonProps { className?: string; onClick?: React.MouseEventHandler<HTMLButtonElement>; children: React.ReactNode; }
内容的提问来源于stack exchange,提问作者Mind Mon
相关产品推荐
相关产品推荐

