React嵌套组件Item中传入Button的onClick事件未触发问题排查
问题原因及修复方案
核心问题
你写的Content组件没有返回JSX元素——函数体里只写了<Container>{content}</Container>,但没有用return语句返回它,也没使用箭头函数的隐式返回语法。这导致Content组件实际渲染的是undefined,你传入的带点击事件的Button根本没被渲染到页面上,自然触发不了点击事件。
修复后的代码
把Content组件改成下面两种写法之一即可:
写法1:添加return语句
interface Props{ content: ReactNode showWithTooltip: boolean } export const Item = ({content, showWithTooltip }: Props) => { const Content = () => { // 加上return返回JSX return <Container>{content}</Container> } return showWithTooltip ? <Tooltip><Content /></Tooltip>: <Content/> }
写法2:使用箭头函数隐式返回
interface Props{ content: ReactNode showWithTooltip: boolean } export const Item = ({content, showWithTooltip }: Props) => { // 用括号包裹JSX实现隐式返回 const Content = () => ( <Container>{content}</Container> ) return showWithTooltip ? <Tooltip><Content /></Tooltip>: <Content/> }
这样修改后,Content组件就能正确渲染传入的Button,点击事件也能正常触发了。
内容的提问来源于stack exchange,提问作者Nghi Nguyen
相关产品推荐
相关产品推荐

