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

如何为作为Prop传入的React组件添加onClick事件

解决React中传递Trigger组件并绑定点击事件的问题

你的问题出在**ComponentB没有接收并传递外部传入的props**,所以ComponentA给Trigger设置的onClick事件根本没有绑定到内部的按钮上。

修复步骤:

  1. 修改ComponentB,让它接收props并传递给内部的<button>:
const ComponentB = (props: React.ButtonHTMLAttributes<HTMLButtonElement>): JSX.Element => {
  // 使用展开运算符把所有props传递给按钮
  return <button {...props}>Click me</button>;
};
  1. 补全ComponentA的Props类型定义(避免TypeScript报错):
import React, { useState } from 'react';

type Props = {
  children: React.ReactNode;
  // 定义Trigger为接收按钮属性的组件类型
  Trigger: React.ComponentType<React.ButtonHTMLAttributes<HTMLButtonElement>>;
};

const ComponentA = ({ children, Trigger }: Props): JSX.Element => {
  const [show, setShow] = useState<boolean>(false);
  return (
    <div>
      <Trigger
        onClick={() => {
          console.log('click');
          setShow(true);
        }}
      />
      {show && children}
    </div>
  );
};

原理说明:

当你把ComponentB作为Trigger传入ComponentA时,ComponentA传递的onClick是组件的props,但原ComponentB没有接收这些props,导致事件无法绑定到按钮。通过{...props}将外部传入的所有属性(包括onClick)传递给内部按钮,就能实现点击触发事件的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:17:09