reactjs - React Native 显示不正确的元素度量

标签 reactjs react-native

我只想得到这个元素的测量值,不真实。

元素

<View style={styles.top}>
    <Animated.View
        style={[styles.textWrapper]}>
        <Text
            onLayout={(event) => {
                this.layout = event.nativeEvent.layout;
            }}
            style={[styles.text]}>Hola</Text>
    </Animated.View>
</View>

样式:

top: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
},
textWrapper: {
    justifyContent: "center",
},
text: {
    position: 'absolute',
    fontSize: 60
}

然后我在 componentDidMount

中记录元素的度量
componentDidMount(){
    setTimeout(()=>{
    const {x, y, height, width} = this.layout;
    console.log('x, y, height, width', x, y, height, width);


    })

///0 , -35.23232323 , 75.3434234234 ,32.22323434

Here's the snack

尽管从视觉上看,该元素位于屏幕中央的某个位置,但您可以看到数字完全错误。

当我可以在屏幕上看到元素时,y 怎么可能是负数呢?

enter image description here

最佳答案

为您的Text元素,你使用了 position: "absolute" style Prop ,但没有提供 lefttopbottomright支柱。 如果添加 left:0, top:0给你的风格 Prop Text元素,然后是 x 的结果和 y将是 0而不是负数:

text: {
    position: 'absolute',
    fontSize: 60,
    left: 0,
    top: 0,
}

最后一个问题:

How can y even be negative when I can see the element is on the screen?

我们可以看到它只是因为没有其他不透明元素覆盖该元素。

关于reactjs - React Native 显示不正确的元素度量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839725/

相关文章:

caching - React Native - 获取调用缓存

android - 如何使用控制台在 React Native Android 中调试 Java 代码

javascript - 有条件的 onChange 函数不起作用

javascript - 子组件更改时刷新应用程序状态

css - flexbox 或 react-css-grid 可以实现这种布局吗?

css - 如何将 CSS 应用于下拉项

javascript - 无法在 firebase 函数中获取 setState

javascript - "Error watching file for changes: EMFILE"当初始化一个 react-native 项目时

css - React - 响应式应用程序 - 最好通过 CSS 隐藏组件中的元素或不渲染它

javascript - React-Native Webview 使用音频播放器可以吗?