为什么点击调整字体时出现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
相关产品推荐
相关产品推荐

