反应本机度量未定义

时间:2018-12-10 11:06:40

标签: react-native scrollview react-native-android

我有一个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'

正如您所见,没有找到度量的方法(我知道这不是找到对象内部内容的最佳方法,但是至少应该在某个地方公开提及,供人们使用,不是吗?

1 个答案:

答案 0 :(得分:0)

您没有正确引用您的视图。那不是将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);
});