You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/TS组件鼠标事件报错:属性不存在于Props类型定义中

解决React+TypeScript组件鼠标事件传递问题

问题根源

你遇到的报错是因为子组件ContentRightHandSide的Props类型未声明onMouseEnter、onMouseLeave和offset属性,TypeScript会严格校验组件接收的props是否匹配定义的类型,传入未声明的属性就会触发类型错误。同时子组件内部没有把父组件传递的鼠标事件绑定到实际DOM元素上,导致事件无法触发。

修复步骤及代码示例

1. 修正子组件的Props类型定义

在ContentRightHandSideProps中补充缺失的属性,建议使用React内置的鼠标事件类型来保证类型安全:

import { ReactNode, MouseEvent } from 'react';

type ContentRightHandSideProps = {
  children?: ReactNode;
  offset?: number; // 补充offset属性,根据业务需求设置为可选或必选
  onMouseEnter?: (e: MouseEvent<HTMLDivElement>) => void;
  onMouseLeave?: (e: MouseEvent<HTMLDivElement>) => void;
};

2. 子组件绑定鼠标事件到DOM元素

把父组件传递的鼠标事件绑定到子组件内部的div上,这样鼠标进入/离开该div时,就会触发父组件的回调:

export function ContentRightHandSide({
  children,
  offset,
  onMouseEnter,
  onMouseLeave,
}: ContentRightHandSideProps) {
  return (
    <div
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      // 如果offset用于样式控制,可在此处添加,比如:style={{ paddingLeft: offset }}
    >
      {children}
    </div>
  );
}

3. 父组件保持原有调用逻辑即可

父组件的代码无需修改,现在传入的onMouseEnter、onMouseLeave和offset都会被TypeScript正确识别:

import { useState } from 'react';
import { ContentRightHandSide } from './ContentRightHandSide';

function ParentComponent() {
  const [isMouseOver, setIsMouseOver] = useState(false);

  return (
    <ContentRightHandSide
      offset={20}
      onMouseEnter={() => setIsMouseOver(true)}
      onMouseLeave={() => setIsMouseOver(false)}
    >
      {/* 子组件内容 */}
    </ContentRightHandSide>
  );
}

额外说明

如果需要子组件内部也处理鼠标事件,可以在绑定事件时添加自定义逻辑,同时保留父组件的回调:

<div
  onMouseEnter={(e) => {
    // 子组件内部逻辑
    console.log('鼠标进入子组件区域');
    // 调用父组件传递的事件,用可选链避免未传入时报错
    onMouseEnter?.(e);
  }}
  onMouseLeave={(e) => {
    console.log('鼠标离开子组件区域');
    onMouseLeave?.(e);
  }}
>
  {children}
</div>

内容的提问来源于stack exchange,提问作者deadant88

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:30:54