如何为作为Prop传入的React组件添加onClick事件
解决React中传递Trigger组件并绑定点击事件的问题
你的问题出在**ComponentB没有接收并传递外部传入的props**,所以ComponentA给Trigger设置的onClick事件根本没有绑定到内部的按钮上。
修复步骤:
- 修改
ComponentB,让它接收props并传递给内部的<button>:
const ComponentB = (props: React.ButtonHTMLAttributes<HTMLButtonElement>): JSX.Element => { // 使用展开运算符把所有props传递给按钮 return <button {...props}>Click me</button>; };
- 补全
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
相关产品推荐
相关产品推荐

