You need to enable JavaScript to run this app. 为什么点击调整字体时出现undefined is not an object(evaluating inputRef.current.incFont)报错
优惠活动
大模型
产品
解决方案
定价
更多

为什么点击调整字体时出现undefined is not an object(evaluating inputRef.current.incFont)报错

问题原因

  • 核心错误出在useImperativeHandle的回调函数写法:你在箭头函数中直接写{incFont: () => {...}, decFont: () => {...}},JavaScript会把大括号识别为函数体的边界,而非要返回的对象,最终没有任何方法暴露给父组件的ref,调用时自然会抛出未定义的报错。
  • 附加潜在问题:你在修改fontSize时直接基于当前state值计算,受闭包影响可能会出现连续点击时更新不符合预期的情况,建议改用函数式更新写法。

修正后的代码

子组件MyInput

const MyInput = React.forwardRef((props,ref) => {
  const [fontSize, setFontSize] = useState(12);

  React.useImperativeHandle(ref,() => ({
    // 箭头函数直接返回对象需要用小括号包裹,避免被识别为函数体
    incFont: () => {setFontSize(prev => prev + 2)},
    decFont: () => {setFontSize(prev => prev - 2)}
  }))
  
  return(
    <TextInput style={{fontSize, borderColor:"red",borderWidth:1}} />
  )
})

父组件代码无需改动,保持原有写法即可:

const inputRef = useRef();
<View>
  <MyInput ref={inputRef}/>
  <Text onPress={()=>inputRef.current.incFont()}>IncreaseFont</Text>
  <Text onPress={() => inputRef.current.decFont()}>DecreaseFont</Text>
</View>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 08:24:01