React Native中按钮文本垂直居中不对齐

6
我遇到了一个问题,就是垂直居中按钮文本时,它始终比确切的中心低一些。我在文档中找到了includeFontPadding,其中提到了一些与第三方字体不一致的问题。 在iOS设备中,字体看起来很正常,但在Android中无法正确居中。 https://facebook.github.io/react-native/docs/text-style-props#includefontpadding 设置为false以删除额外的字体填充,以便为某些上升/下降部分留出空间。对于某些字体,这种填充会使文本在垂直居中时看起来稍微有些不对齐。为了获得最佳效果,请将textAlignVertical也设置为center。默认值为true。
<Button
    style={[style.button]} block >
     <Text>Setup Now</Text>
  </Button>
export default {
  button: {
    elevation: null,
    shadowColor: null,
    shadowOffset: null,
    shadowOpacity: null,
    shadowRadius: null
  }
}

enter image description here


3
请同时添加使用的样式。 - Tim
@Tim风格已添加 - technerd
你正在使用标准的react-native按钮吗? - Tim
@Tim:是的,我正在使用标准按钮。 - technerd
很抱歉再次提问,您能否提供一个 MCVE?否则我想没人能帮到您。 - Tim
显示剩余3条评论
5个回答

5

不要在按钮组件(Button Component)内部使用文本(Text component); 直接使用 Button Documentation 中定义的 "title" 属性:

https://facebook.github.io/react-native/docs/button.html

因此您的代码将如下所示:

<Button
    style={[style.button]} title="Setup Now" block >
  </Button>

请问您能否发布带有输出结果的屏幕截图? - technerd

4

试试这个:

<Button style={{display: 'flex', justifyContent: 'center'}}>
   <Text>Setup Now</Text>
</Button>

3
如果您正在使用React Native默认按钮,则React Native默认按钮不支持样式属性。同时,应该使用“标题”属性代替在按钮组件中使用Text组件。有关详细信息,请参阅官方文档中定义的“title”属性。请参考以下链接。

https://facebook.github.io/react-native/docs/button.html

此外,React Native为您提供了各种按钮选项,以便您自定义按钮并根据您的使用进行选择。有关详细信息,请参阅以下链接。

https://facebook.github.io/react-native/docs/handling-touches

请尝试以下解决方案,可能有助于您的问题。

<TouchableOpacity
      activeOpacity={.5}
      style={styles.buttonStyle}>
      <Text style={styles.textStyle}>Setup Now</Text>
</TouchableOpacity>



buttonStyle: {
    padding: 14,
    backgroundColor: 'red',
    borderRadius: 6,
  },

  textStyle: {
    color: 'white',
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 16,
  },

0
你可以尝试为文本添加一些样式。实际上,在你从文档中引用的代码片段中直接提到了这一点:

为了获得最佳效果,还应将textAlignVertical设置为center。

<Text style={[style.text]}>Setup now</Text>

使用这些样式:

export default {
  button: {
    ...
  },
  text: {
    flex: 1,   // fill the button
    textAlign: 'center',
    textAlignVertical: 'center',  // this style is Android only
  }
}

0

你可以在文本中添加样式,例如:<Text style={styles.example}>测试</Text>,然后将其添加到你的样式表中:

const styles = StyleSheet.create({ example: { textAlign:'center', } })

这可能对你的参考有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接