react-native - 反应原生措施未定义
问题描述
我有一个 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'
正如你所看到的那样,没有找到措施(我知道它不是找到物体内部的最佳方法,但至少应该在某个地方公开提及以供人们使用,不是吗?
解决方案
您没有正确引用您的视图。这不是如何将 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);
});
推荐阅读
- python - NumPy 中傅里叶相移在图像翻译中的伪影
- r - 如何拆分值的数据帧并在块上使用 rle?
- docker - AWS Codepipeline:“手动”工作,但无法让 terraform 设置阶段
- python - How to filter part of a function's output
- spring-cloud - 使用 Spring Cloud Contracts 时,为什么生产者要创建合约?
- django - 无法将模型导入 celery tasks.py 文件
- c++ - 使用 std::sort 对自定义类的智能指针进行排序
- python - 如何使用flask web api直播我的音频输入
- makefile - 使 .SECONDEXPANSION 配方执行两次
- python - 预测依据历史数据