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

子组件自带onClick时,父组件传递onClick报错的解决方法

问题解决:React父子组件点击事件的TypeScript类型错误

组件代码

父组件Overview

export default function Overview() {
  const selectPlantHandler = () => {
    console.log("add to selection");
  }

  return (
        <div>
          {plants.map((element, index) => {
            return (
              <PlantCard key={index} 
                         onClick={selectPlantHandler}>
                 Herbert
              </PlantCard>
            );
          })}
        </div>
  );
}

子组件PlantCard

export default function PlantCard({ children } : { children: any }) {
  const [isActive, setIsActive] = useState(false);

  function onClickHandler() {
    setIsActive(!isActive);
  }

  return (
    <div onClick={onClickHandler} isActive={isActive}>
        <h3>{children}</h3>
    </div>
  );
}

遇到的TypeScript错误

Type '{ children: string; key: number; onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & { children: any; }'.
Property 'onClick' does not exist on type 'IntrinsicAttributes & { children: any; }'.

解决方案

问题核心是子组件PlantCard的Props类型未声明onClick属性,导致TypeScript判定父组件传入的onClick为无效属性。同时需要让子组件点击时同时完成自身状态更新和父组件回调触发,具体修改如下:

  1. 扩展子组件Props类型,添加可选的onClick回调定义:
type PlantCardProps = {
  children: any;
  onClick?: () => void;
};
  1. 修改子组件点击处理逻辑,先更新自身状态,再调用父组件传入的onClick(需判断回调是否存在,避免调用undefined):
function onClickHandler() {
  setIsActive(!isActive);
  props.onClick?.();
}
  1. 完整修改后的PlantCard代码:
import { useState } from 'react';

type PlantCardProps = {
  children: any;
  onClick?: () => void;
};

export default function PlantCard(props: PlantCardProps) {
  const [isActive, setIsActive] = useState(false);

  function onClickHandler() {
    setIsActive(!isActive);
    props.onClick?.();
  }

  return (
    <div onClick={onClickHandler} isActive={isActive}>
        <h3>{props.children}</h3>
    </div>
  );
}

修改完成后,TypeScript错误会消除,点击PlantCard时会先切换自身isActive状态,再触发父组件的selectPlantHandler逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:24:25