【问题标题】:React navigation Get stack navigator header height inside class component (without hooks)反应导航获取类组件内的堆栈导航器标题高度(无挂钩)
【发布时间】:2020-11-05 14:32:20
【问题描述】:

我知道可以使用以下钩子 (V5) 获取堆栈头高度:

import { useHeaderHeight } from '@react-navigation/stack';

类组件有解决方法吗?目前我正在使用上下文消费者来获取 render() 函数中的高度:

<HeaderHeightContext.Consumer>
                  {headerHeight => (   
    ...
    )}
</HeaderHeightContext.Consumer>

但我想在我的 render() 函数之外使用 headerHeight。

【问题讨论】:

    标签: react-native react-navigation react-navigation-v5


    【解决方案1】:

    你有没有在你的组件中尝试过这样的事情:

    static contextType = HeaderHeightContext;
    
    componentDidMount() {
       console.log(this.context); // this is your height
    }
    

    来自documentation

    可以为类的 contextType 属性分配一个由 React.createContext() 创建的 Context 对象。这使您可以使用 this.context 使用该 Context 类型的最接近的当前值

    【讨论】:

    • 我收到一个:TypeError: undefined is not an object (evaluating '_this.context.headerHeight')
    • 我的测试方法如下:class AddProductScreen extends React.Component { static contextType = HeaderHeightContext; constructor(props) { super(props); const { headerHeight } = this.context; console.log(headerHeight); ... }
    • 没有更多错误,但 headerHeight 值为undefined
    • 56 我想这就是我要找的东西?你能解释一下我们是怎么得到的吗?
    猜你喜欢
    • 2020-01-28
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2020-07-14
    • 2020-11-19
    • 2017-11-25
    相关资源
    最近更新 更多