从react-navigation扩展默认Header以组成一个新组件

时间:2019-11-29 12:42:34

标签: react-native react-navigation react-navigation-stack

如何在react-navigation中实现从默认Header组件扩展的ThemedHeader?我已经尝试过这样的事情:

作为类组件

import React, {PureComponent} from 'react';
import {Header, HeaderProps} from 'react-navigation-stack';
import {StyleSheet} from 'react-native';
import {ThemeContext} from 'styled-components';

export default class ThemedHeader extends PureComponent<HeaderProps> {
  static contextType = ThemeContext;

  render() {
    const {scene} = this.props;
    const {colors} = this.context;

    const headerStyleObj = StyleSheet.flatten(
      scene.descriptor.options.headerStyle,
    );

    const themedScene = {
      ...scene,
      descriptor: {
        ...scene.descriptor,
        options: {
          ...scene.descriptor.options,
          headerTintColor: colors.accent,
          headerStyle: {
            backgroundColor: colors.primary,
            ...headerStyleObj,
          },
        },
      },
    };

    //@ts-ignore
    return <Header {...props} scene={themedScene} />;
  }
}

,并在header中定义为navigationOptions时返回以下错误:

class component error

作为功能组件:

import React, {useMemo} from 'react';
import {Header, HeaderProps} from 'react-navigation-stack';
import {useTheme} from 'react-native-paper';
import {StyleSheet} from 'react-native';
import {Theme} from 'react-native-paper/lib/typescript/src/types';
import {ThemeContext} from 'styled-components';

export default function ThemedHeader(props: HeaderProps, context: Theme) {
  const {scene} = props;
  const {colors} = useTheme();

  const headerStyleObj = StyleSheet.flatten(
    scene.descriptor.options.headerStyle,
  );

  const themedScene = {
    ...scene,
    descriptor: {
      ...scene.descriptor,
      options: {
        ...scene.descriptor.options,
        headerTintColor: colors.accent,
        headerStyle: {
          backgroundColor: colors.primary,
          ...headerStyleObj,
        },
      },
    },
  };

  //@ts-ignore
  return <Header {...props} scene={themedScene} />;
}

,并在header中定义为navigationOptions时返回以下错误:

function component errro

1 个答案:

答案 0 :(得分:0)

解决了在ThemedHeader的{​​{1}}上将props => <ThemedHeader {...props} />作为内嵌渲染函数header传递的问题