React钩子useRef()变量在Android上为null,但在iOS上有效

时间:2019-09-18 18:01:20

标签: javascript reactjs react-native react-hooks

所以我有一个组件,该组件由一个组件包装,该组件具有引用:

const viewRef = useRef(null);
...
<View ref={ viewRef }>

该组件还具有在按下时触发的功能

// locationX is the location of tapping relative to <View>
const tapSliderGesture = (locationX) => {
  // we need the ViewRef to measure its size (width) and position relative to screen (px)
  viewRef.current.measure((fx, fy, width, height, px) => {
    const location = Math.round(((locationX - px) / width) * steps);
    if (location !== state) {
      setState(location);
    }
  });
};
...
<View ref={ viewRef } onResponderMove={ (evt) => { tapSliderGesture(evt.nativeEvent.locationX); } }>

但是,在Android ViewRef.current上,tapSliderGesture内始终为null,很有趣的是,ViewRef.current在组件内和{{1}外为 not null }。

下面的完整示例:

tapSliderGesture

1 个答案:

答案 0 :(得分:0)

所以问题是android进行了某种优化,从而改变了DOM层次树。答案是在我的视图中添加collapsable: false道具,所以:

<View ref={ viewRef } collapsable={ false } .../>

那已经解决了...

https://github.com/facebook/react-native/issues/3282

提到的另一种解决方法是向视图节点onLayout添加一个空的onLayout={() => {}}道具