以编程方式检索 Header 组件高度 - React Native

programmatically retrieve Header component height - React Native

使用 NativeBase,我添加了一个 Header 组件。现在,我想以编程方式检索 header 的高度。我怎样才能做到这一点。添加Header的代码如下:

我尝试使用 Dimensions.get('window') 但它给了我整个视图的高度。

代码:

import React, {Component} from 'react-native';
import {Container, Header, Button, Title, Icon} from 'native-base';
​
export default class ThemeHeaderExample extends Component {
    render() {
        return (
                <Header>
                    <Button transparent />

                    <Title>Header</Title>

                </Header>
        );
    }
}

我不使用 native base 但你应该可以使用 onLayout 道具: https://facebook.github.io/react-native/docs/view.html#onlayout

遗憾的是,NativeBase.Header 没有暴露高度。

我遇到了同样的问题,我深入研究了代码,我意识到高度是这样编码的:

toolbarHeight: platform === "ios" ? 64 : 56

查看 here at line 155. You will end up there following Header Component300.

尽管这可能有效,但这似乎不是我们想要做的事情,或者至少,固定的解决方案似乎很丑陋。

因此,我所做的是创建自己的页眉,这非常简单明了,因为它只是一个包装器,并使用 "refs measure" 函数让我们获得位置和大小。你可以看一个例子 here.

基本上,它应该是这样的:

render() {
    return (
      <View style={styles.container} ref="yourComponent">
        <TouchableOpacity onPress={this.measureYourComponent}>
          <Text>Measure it</Text>
        </TouchableOpacity>
      </View>
    );
}

measureYourComponent() {
    this.refs.yourComponent.measure((ox, oy, width, height, px, py) => {
        console.log("ox: " + ox); //Relative position
        console.log("oy: " + oy); //Relative position
        console.log("width: " + width);
        console.log("height: " + height);
        console.log("px: " + px); //Absolute position
        console.log("py: " + py); //Absolute position
      });
}

在我的例子中,我需要根据 child 的大小对某些 parent 做出反应,因此将 OnPress 处理程序替换为其 parent 提供的处理程序。

这样,尽管您需要付出更多的努力,但您将拥有一个更灵活和可重用的解决方案。

如果有什么需要澄清的,请告诉我。

我通过导入变量并使用它解决了它。

import toolbarHeight from '../../native-base-theme/variables/platform'

我遇到了同样的问题,我就是这样解决的。

使用您想要的高度(例如 20)和 paddingTop 为 0 的样式。

<Header style={{height: 20, paddingTop:0}}>
    <Button transparent />

    <Title>Header</Title>

</Header>

希望对您有所帮助:)

我的 iPhone X 我的 native base Header was adding padding from the top when I use SafeAreaView 遇到问题,然后我提出了以下解决方法,它可能会解决您的问题。

我已经在 iPhone X、8 和 android.

上进行了测试
import {StatusBar, TouchableOpacity, View, SafeAreaView,platform,Dimensions} from "react-native";
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
const platformStyle = undefined;

const isIphoneX =
Platform.OS === 'ios' &&
(deviceHeight === 812 ||
deviceWidth === 812 ||
deviceHeight === 896 ||
deviceWidth === 896);

<Header style={{paddingTop: isIphoneX ? -10 : 15,maxHeight:50,minHeight:50}}>