首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在react-native-paper中居中Appbar.Header标题?

如何在react-native-paper中居中Appbar.Header标题?
EN

Stack Overflow用户
提问于 2019-01-10 07:34:00
回答 6查看 6.5K关注 0票数 9

正如您在docs中看到的,react-native-paper中标题的默认位置是左对齐的。我已经看过很多关于如何在Android Native和React Native的StackNavigator上实现居中标题的问题和答案,但我没有幸运地用react-native-paper实现同样的效果。

到目前为止,我已经尝试在Appbar.Header中使用style参数传入{ textAlign: 'center' }{ flexDirection: 'row', justifyContent: 'space-between' },但似乎都不起作用。react-native-paper缺乏关于重写的文档,这给我留下的印象不是很深刻,但我仍然希望有一种方法可以完成我正在寻找的事情。

代码语言:javascript
复制
const styles = { header: { textAlign: 'center' }}

<Appbar.Header style={styles.header}>
  <Appbar.Action icon="close" onPress={() => this.close()} />
  <Appbar.Content title={title} />
  <Button mode="text" onPress={() => this.submit()}>
    DONE
  </Button>
</Appbar.Header>

考虑到title接受一个node,它可以用来显示一个react组件。

如何在所有设备上强制标题居中?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2020-01-17 21:56:32

react-navigation允许为title传递组件,而不是字符串,所以我们可以在这里做同样的事情:

我写了一个例子,它接受一个自定义的标题组件,并且可以在我们想要的任何地方使用:

代码语言:javascript
复制
import * as React from 'react';
import { Appbar, Button, Text } from 'react-native-paper';

const ContentTitle = ({ title, style }) => (
  <Appbar.Content
    title={<Text style={style}> {title} </Text>}
    style={{ alignItems: 'center' }}
  />
);

const App = () => (
  <Appbar.Header> 
    <Appbar.Action icon="close" onPress={() => this.close()} />
    <ContentTitle title={'Title'} style={{color:'white'}} />
    <Button mode="text" onPress={() => this.submit()}>
      DONE
    </Button>
  </Appbar.Header>
);

export default App;

你可以查看:https://snack.expo.io/r1VyfH1WL

票数 6
EN

Stack Overflow用户

发布于 2019-05-31 05:56:02

您必须使用titleStyle而不是style来使文本居中。下面的代码对我来说是有效的。

代码语言:javascript
复制
<Appbar.Header>
  <Appbar.Content titleStyle={{textAlign: 'center'}} title="Centered Title" />
</Appbar.Header>

还有一个类似的subtitleStyle用于设置字幕的样式。Check the docs for more info

票数 2
EN

Stack Overflow用户

发布于 2021-03-26 16:04:47

有两种方法可以解决这个问题。

首先,Appbar.Content应用了marginLeft。因此,您只需将marginLeft设置为0。

代码语言:javascript
复制
<Appbar.Header>
  <Appbar.BackAction />
  <Appbar.Content title='Title' style={{ marginLeft: 0 }} titleStyle={{ marginLeft: 0 }} />
  // Put empty action here or any action you would like to have
  <Appbar.Action/>
</Appbar.Header>

遗憾的是,这种方法只允许在右侧执行一个菜单操作。(或者有相同数量的左右动作,但我认为只有一个菜单动作会出现在左侧,那就是后退按钮)

其次,使Appbar.Content具有absolute位置。是的,将marginLeft保持为0。

代码语言:javascript
复制
<Appbar.Content title='Title' 
  style={{ marginLeft: 0, position: 'absolute', left: 0, right: 0, zIndex: -1 }} 
  titleStyle={{ alignSelf: 'center' }} />

我们需要将zIndex设置为-1 (或更低),以便可以单击按钮/菜单操作。这样,您可以有多个菜单操作。

第一种方法很简单,但有局限性,而第二种方法功能强大,但需要编写更多的代码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54120003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档