reactjs - 为什么我得到“未定义不是对象(评估“inputRef.current.incFont”?
问题描述
它没有做我想要的。
我有两个textArea,我使用它们,因为它们是按钮。一个会增加 FontSize,另一个会减少它。
当我单击reduceFont文本时,我收到该错误。
这是我添加的代码,
const MyInput = React.forwardRef((props,ref) => {
const [fontSize, setFontSize] = useState(12);
React.useImperativeHandle(ref,() => {
incFont: () => {setFontSize(fontSize+2)}
decFont: () => {setFontSize(fontSize-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>
解决方案
改变useImperativeHandle
如下,
React.useImperativeHandle(ref, () => ({
incFont: () => {
setFontSize(fontSize + 2);
},
decFont: () => {
setFontSize(fontSize - 2);
}
}));
工作代码 - https://codesandbox.io/s/distracted-burnell-0h70g?file=/src/App.js
推荐阅读
- python - 编写一个函数,当函数参数是列表的值时,返回列表中项目的索引
- electron - 我应该如何在 Electron 中组织我的代码?
- r - 计算数据框中一行的中位数并保存到新变量
- symfony - Typo3 - 如何在 symfony commandController 中获取 extbase 上下文
- html - html 将环境变量注册为未定义
- php - pecl install - 如何指定选项?
- flutter - image_picker_modern 在 android 模拟器上运行时导致构建失败
- vb.net - 如何使用 numeric up down 来检索 datagridview 插入的结果或插入到 datagridview 的过去数据?
- sed - SED 将模式保留在 \1 中以用于下一个块/命令
- prometheus - 千分尺/普罗米修斯:如何测量处理持续时间?