使用useRef获取高度和宽度给我TypeError

时间:2019-12-04 03:18:00

标签: javascript reactjs react-native react-hooks

我正在尝试使用height获取width的{​​{1}}和TextInput,但一直为空。

首先,我尝试了两种不同的方式来初始化引用:

useRef

const inputRef = useRef(React.createRef)

我已经将它们与其中之一匹配:

const inputRef = useRef(null)

useLayoutEffect(() => {
    console.log("inputRef.current.clientHeight", inputRef.current.clientWidth)      
})

我正在尝试从中获取尺寸的元素:

useEffect(() => {
    console.log("inputRef.current.clientHeight", inputRef.current.clientWidth)      
})

但是,出现以下错误

  

TypeError:TypeError:null不是对象(正在评估   'inputRef.current.clientWidth')

1 个答案:

答案 0 :(得分:0)

React Native本机组件布局与Web API共享的属性不同。

要访问布局信息,文档建议使用onLayout,但也可以选择onContentSizeChange

如果您想对它们的属性以及它们的名称进行目视检查,我已复制了少量点心:https://snack.expo.io/@ezrayoung/crabby-popsicle(要查看控制台,请单击底部的“编辑器”按钮,然后启用面板选项)