React Typescript自定义Item子组件onClick点击事件无响应问题求助
问题根因
- 父组件给自定义Item组件传递
onClick的写法错误,绑定的箭头函数只返回了changeActive函数本身,没有执行实际逻辑,因此点击无响应也不会触发报错 - 父子组件的
onClick参数类型定义不匹配
解决步骤
- 修正父组件的事件绑定写法
你当前的Item组件onClick写的是() => this.changeActive,仅返回函数未执行,补充调用括号和需要传入的布尔参数即可。按照你的切换逻辑,两个Item分别传入对应的值:
<div className="box--vertical"> <Item htitle="Ivory White" onClick={() => this.changeActive(true)} active={ this.state.color ? 'active' : ' ' } text="For the past 75 years, Sennheiser has put sound first. The new MOMENTUM True." price=" " /> <Item htitle="Matte Black" onClick={() => this.changeActive(false)} active={ this.state.color ? ' ' : 'active' } text="Of all of the celestial bodies that capture our attention and fascination as astronomers." price=" " /> </div>
- 可选:优化子组件类型定义
如果你不需要使用子组件点击时的原生鼠标事件,可以调整Item组件的Props接口,和父组件传递的函数类型更匹配:
interface Props { active: string, htitle: string, text: string, price: string, onClick: () => void };
补充说明
如果需要使用点击事件的原生对象,也可以在父组件的箭头函数中接收后按需处理,写法如下:
onClick={(e) => { // 可在这里处理e事件对象 this.changeActive(true) }}
内容的提问来源于stack exchange,提问作者dalvenjha
相关产品推荐
相关产品推荐

