React使用useRef hook处理onKeyDown事件及forwardRef使用问题咨询
问题排查与修复方案
核心错误点
- forwardRef语法错误:
forwardRef包裹的组件函数必须接收两个入参,第一个是组件自身的props,第二个是需要转发的ref对象。你的代码既没有接收第二个ref参数,还错误地把第一个props的类型标注为ref,直接触发编辑器报错。 - ref传递逻辑错误:你在渲染初期就把
findsGoodsBtnRef.current赋值给findGoodsBtn,此时组件未挂载,current初始值为null,且后续ref更新时该变量不会同步更新,传给CcceAttribute的ref永远是无效值。 - 键盘事件判断错误:
event.keyCode返回值为数字类型,你用字符串"13"做判断永远匹配失败,无法触发点击逻辑。更推荐使用标准写法event.key === 'Enter',兼容性更强。 - 变量名不匹配错误:解构props时你用的是
...props,但给StringAttributeDefault传递剩余属性时写的是...otherProps,变量名不一致会直接触发运行时报错。 - 子组件ref暴露缺失:如果
CcceAttribute本身没有用forwardRef包裹,你直接给它传ref属性是无效的,需要先改造CcceAttribute,把内部的按钮ref对外暴露。
修复后参考代码
// 先确认CcceAttribute已经用forwardRef包裹,能正确接收ref并绑定到内部按钮上 const CcceAttribute = forwardRef<HTMLButtonElement, CcceAttributeProps>((props, ref) => { // 内部原有逻辑保持不变 return <button ref={ref} {...props}>查询商品</button> }) const CommodityCodeLookupAttribute = forwardRef<HTMLButtonElement, Props>( ({ attribute: productLookupAttribute, onChange, ...otherProps }, ref) => { const { object } = useFormObjectContext(); const ccceAttribute = object.attributeCollection.find(isCcceResultAttribute); if (!ccceAttribute) { return null; } const findsGoodsBtnRef = React.useRef<HTMLButtonElement>(null); const handleOnKeyDown = (event: React.KeyboardEvent) => { if (event.key === "Enter") { event.preventDefault(); console.log("Default prevented"); findsGoodsBtnRef.current?.click(); } }; // 如果需要把内部按钮的ref转发给当前组件的外部父组件,保留下面这行,不需要可以删除 useImperativeHandle(ref, () => findsGoodsBtnRef.current as HTMLButtonElement); return ( <> <StringAttributeDefault attribute={productLookupAttribute} onKeyDown={handleOnKeyDown} {...otherProps} /> {/* 直接传递ref对象,不要提前取current */} <CcceAttribute attribute={ccceAttribute} ref={findsGoodsBtnRef} /> </> ); });
内容的提问来源于stack exchange,提问作者cts
相关产品推荐
相关产品推荐

