使用 react-navigation 包装 multi-line 自定义 header

Wrapping multi-line custom header using react-navigation

我正在使用嵌入在抽屉导航器中的 react-navigation 堆栈导航器。如果 header 文本很长,我希望 header 文本有两行。这是我尝试过的:

 static navigationOptions = ({ navigation }) => {
    return {
        title: (
            <Text 
                numberOfLines = {2}
            >
                Let's see how long the title can be
            </Text>
        ),
        headerTitleStyle: 
            {
                color: Colors.ORANGE, 
            },
        headerTintColor: Colors.ORANGE,
        headerRight: 
          <MenuIcon 
              navigation = {navigation}  
          />,
    };
};

这行不通。相反,标题显示为 "Let's see how lo..."。当我尝试在我的其中一个屏幕中创建类似的文本组件时,它会按预期换行文本。

如何使用 react-navigation 实现 multi-line 标题?

有两个属性会影响导航栏的标题:title,一个纯字符串,和 headerTitle,一个接收标题作为 children 属性的反应组件,允许您覆盖它的呈现方式。在这种情况下,要使标题呈现在两行上,请将以下内容添加到 navigationOptions:

headerTitle: ({ style, children : title }) => {
  return (
    <Text style={style} numberOfLines={2}>{title}</Text>
  )
},

这就是我最终使用的标题中有2行文字的内容:

static navigationOptions = ({ navigation }) => {
        return {
            title: (
                <View 
                    style = {{width: 220, height: 50}}
                >
                    <Text 
                        numberOfLines = {2} 
                        style = {{color: Colors.ORANGE, fontWeight: '700', fontSize: 14, textAlign: 'center', marginRight: 60, marginTop: 12}}
                    >
                        Let's see how long the title can be
                    </Text>
                </View>
            ),
            headerTintColor: Colors.ORANGE,
            headerRight: 
          <MenuIcon 
              navigation = {navigation}  
          />,
        };
    }

header 的固定 width 不能在所有屏幕尺寸上正常工作。

我做的是设置百分比宽度和设置绝对位置。

const HeaderTitle = (props) => {

  return <Text
        style={{
          width    : "80%",
          position : "absolute",
          top      : 0,
        }}
        numberOfLines={2}
        {...props}>
          {props.children}
        </Text>
}

navigationOptions : ({ screenProps: { t } }) => ({
  headerTitle : () => <HeaderTitle>This is a very very long headertitle, that you can choose to break into multiple lines by changing numberOfLines property</HeaderTitle>,
}),