首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我要得到“未定义的不是一个对象”(计算"inputRef.current.incFont“)?

为什么我要得到“未定义的不是一个对象”(计算"inputRef.current.incFont“)?
EN

Stack Overflow用户
提问于 2021-07-06 13:57:02
回答 1查看 108关注 0票数 0

它不能做我想做的事。

我有两个textArea,我把它们当作按钮使用。一个会增加FontSize,另一个会降低它。

当我点击decreaseFont文本时,我会得到这个错误。

这是我添加的代码,

代码语言:javascript
复制
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}} />
  )


})

在我的主要功能中:

代码语言:javascript
复制
 const inputRef = useRef();
<View>
 <MyInput ref={inputRef}/>
          <Text onPress={()=>inputRef.current.incFont()}>IncreaseFont</Text>
          <Text onPress={() => inputRef.current.decFont()}>DecreaseFont</Text>

        </View>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-06 14:51:40

更改useImperativeHandle如下,

代码语言:javascript
复制
React.useImperativeHandle(ref, () => ({
    incFont: () => {
      setFontSize(fontSize + 2);
    },
    decFont: () => {
      setFontSize(fontSize - 2);
    }
  }));

工作代码- https://codesandbox.io/s/distracted-burnell-0h70g?file=/src/App.js

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68271931

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档