首页 > 解决方案 > 反应原生措施未定义

问题描述

我有一个 ScrollView,其中有几个 View lick 所以

<ScrollView>
    <View
        ref = {"view1"}
        style = {{
            height: 200,
            backgroundColor: "#FF0000"
        }}
    >
        <Text>{"text 1"}</Text>
    </View>
    <View
        ref = {"view2"}
        style = {{
            height: 200,
            backgroundColor: "#FF0000"
        }}
    >
        <Text>{"text2"}</Text>
    </View>
</ScrollView>

按下启动此代码时,我有一个 2 按钮

// buttonPress is either "view1" || "view2"
this.refs[buttonPress].measure((fx, fy, width, height, px, py) => {
    console.log("Fy", fy);
    console.log("Py", py);
});

但是我错误地说该度量是未定义的,实际上我可以正确地获得参考我确定了这一点,但是当我在这里打印对象内的所有键时会出现什么:

11:38:28.404 I 'KEY', 'props'
11:38:28.404 I 'KEY', 'context'
11:38:28.404 I 'KEY', 'refs'
11:38:28.405 I 'KEY', 'updater'
11:38:28.405 I 'KEY', 'setWrappedInstance'
11:38:28.405 I 'KEY', 'resolveConnectedComponentStyle'
11:38:28.405 I 'KEY', 'state'
11:38:28.405 I 'KEY', '_reactInternalFiber'
11:38:28.405 I 'KEY', '_reactInternalInstance'
11:38:28.405 I 'KEY', '__reactInternalMemoizedUnmaskedChildContext'
11:38:28.405 I 'KEY', '__reactInternalMemoizedMaskedChildContext'
11:38:28.405 I 'KEY', '__reactInternalMemoizedMergedChildContext'
11:38:28.405 I 'KEY', '_root'
11:38:28.406 I 'KEY', 'wrappedInstance'
11:38:28.406 I 'KEY', 'isReactComponent'
11:38:28.406 I 'KEY', 'setState'
11:38:28.406 I 'KEY', 'forceUpdate'

正如你所看到的那样,没有找到措施(我知道它不是找到物体内部的最佳方法,但至少应该在某个地方公开提及以供人们使用,不是吗?

标签: react-nativescrollviewreact-native-android

解决方案


您没有正确引用您的视图。这不是如何将 ref prop 传递给视图。尽管有一个新的 API 可以做到这一点。旧方法是使用回调。这就是你的代码应该是这样的:

Import React, {createRef} from 'react';
import {ScrollView, View} from 'react-native';

const firstView = createRef(null);
const secondView = null

<ScrollView>

<View
    ref = {firstView}
    style = {{
        height: 200,
        backgroundColor: "#FF0000"
    }}
>
    <Text>{"text 1"}</Text>
</View>
<View
    ref = {view => secondView = view}
    style = {{
        height: 200,
        backgroundColor: "#FF0000"
    }}
>
    <Text>{"text2"}</Text>
</View>

然后稍后在您的句柄中,您可以使用以下内容访问两个视图:

// first view is using the new API

firstView.current.measure((x, y, width, height, pagex, pagey) => {
console.log('x coordiante: ', pagex);
console.log('y coordinate: ', pagey);
});

// secondView is using the old API

secondView.measure((x, y, width, height, pagex, pagey) => {
console.log('x coordiante: ', pagex);
console.log('y coordinate: ', pagey);
});

推荐阅读