【问题标题】:Button text not aligned center vertically in react native按钮文本在本机反应中未垂直居中对齐
【发布时间】:2019-09-28 00:50:12
【问题描述】:

我面临一个问题,将按钮的文本垂直居中对齐,但它仍然略低于正中。 我从文档中找到了includeFontPadding,它暗示了某些第三方字体存在一些差异。

字体在 iOS 设备中看起来很合适,但在 Android 设备中不正确。

https://facebook.github.io/react-native/docs/text-style-props#includefontpadding

设置为 false 以删除旨在为某些上升/下降腾出空间的额外字体填充。对于某些字体,此填充可能会使文本在垂直居中时看起来略微错位。为了获得最佳结果,还将 textAlignVertical 设置为居中。默认为真。

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

按钮样式:

export default {
  button: {
    elevation: null,
    shadowColor: null,
    shadowOffset: null,
    shadowOpacity: null,
    shadowRadius: null
  }
}

【问题讨论】:

  • 请同时添加使用的样式。
  • @Tim 样式添加
  • 你使用的是标准的 react-native 按钮吗?
  • @Tim:是的,我使用的是标准按钮
  • 抱歉再次提问,能否提供MCVE?我认为否则没有人可以帮助你

标签: android reactjs react-native styles text-alignment


【解决方案1】:

而不是在按钮组件中使用文本组件。 使用按钮文档中定义的道具“标题”:

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

所以你的代码将是

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

【讨论】:

  • 能否请您发布带有输出的屏幕?
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    如果您使用的是 react native 默认按钮,则 react native 默认按钮不支持样式属性,并且不支持在 Button 组件中使用 Text 组件。使用官方文档中定义的属性“标题”,请参考以下链接

    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,
      },
    

    【讨论】:

      【解决方案4】:

      您可以尝试为您的文本添加一些样式。实际上,您从文档中引用的那个片段中直接提到了它:

      为了获得最佳效果,还将 textAlignVertical 设置为居中。

      <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
        }
      }
      

      【讨论】:

        【解决方案5】:

        或者您可以在文本中添加样式,例如 &lt;Text style={styles.example}&gt;TEST&lt;/Text&gt;,然后添加到您的样式中

        const styles = StyleSheet.create({ example: { text-align:'center', } })

        也许这可以帮助你参考

        【讨论】:

          猜你喜欢
          • 2021-10-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-06
          • 2013-05-25
          • 2013-06-04
          • 1970-01-01
          • 2012-09-14
          • 2022-08-18
          相关资源
          最近更新 更多