首页 > 解决方案 > 为什么我得到“未定义不是对象(评估“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>

标签: reactjsreact-native

解决方案


改变useImperativeHandle如下,

React.useImperativeHandle(ref, () => ({
    incFont: () => {
      setFontSize(fontSize + 2);
    },
    decFont: () => {
      setFontSize(fontSize - 2);
    }
  }));

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


推荐阅读