返回 导航

React / React Native

hangge.com

React Native - Text组件使用详解(样式、属性、方法)

作者:hangge | 2017-01-23 08:10
Text 一个用于显示文本的 React 组件,并且它也支持嵌套、样式,以及触摸处理。


1,简单的样例

(1)效果图
下面给 Text 设置了字体大小、颜色、阴影,并加粗。

(2)样例代码
 import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
 } from 'react-native';

class Main extends Component {
   render() {
     return (
      <View style={[styles.flex, styles.container]}>
        <Text style={styles.font}>编程社区</Text>
      </View>
     );
   }
 }

 const styles = StyleSheet.create({
   flex:{
       flex:1
   },
   container: {
    marginTop:35,
    marginLeft:5,
    marginRight:5,
  },
  font:{
    color:'#FF7700',
    fontSize:40,
    fontWeight:'bold',
    textShadowColor:'#C0C0C0',
    textShadowRadius:2,
    textShadowOffset:{width:2,height:2},
  },
 });

 AppRegistry.registerComponent('HelloWorld', () => Main);

2,Text支持的样式

Text 组件除了可以使用 View 组件所有的 Style,还支持如下样式:
 名称 作用 适用设备
 color  字体颜色  多种形式  通用
 fontFamily  字体名称
fontFamily 用来指定 Text 组件以何种字体族显示。它的取值有:
  • serif:该字体族在字的笔画开始及结束的地方有额外的装饰,而笔画的粗细会因横直地不同而有所不同。
  • sans-serif:该字体族没有额外的装饰,笔画粗细大致差不多。
  • monospace:由于打字机的出现,又独立出了这种等宽字体种类。
以及延伸出来的:sans-serif-light、sans-serif-thin、sans-serif-condensed、sans-serif-medium
 通用
 fontSize  字体大小  数字  通用
 fontStyle  字体风格  normal、italic  通用
 fontWeight  字体粗细权重  normal、bold、100、200、300、400、500、600、700、800、900
 normal和bold适用于大多数字体,分别表示正常字体和粗体。
 其后的9个数字序列代表从最细(100)到最粗(900)的字体粗细程度,每一个数字定义的粗细都要比上一个等级稍微粗一些。但不是所有的字体的值都能用数字值,在这种情况下,最接近的值被选择。
 通用
 lineHeight  行高  数字  通用
 textAlign  文本对齐方法  auto、left、right、center、justify。
 auto表示根据组件显示的字符语言来决定字符串如何排列,比如英语将自动从左向右排列,而阿拉伯语将自动从右向左排列。
 justify值只支持iOS,在Android上会自动回退到left。
 通用
 textDecorationLine  横线位置  none、underline、line-through、underline line-through  通用
 textShadowColor  阴影效果颜色  多种形式  通用
 textShadowOffset  设置阴影效果  {width:number,height:number}  通用
 textShadowRadius  阴影效果圆角  数字  通用
 includeFontPadding  文本是否包含顶部和底部额外空白  默认为:true。即显示字符串时提供了额外的字体填充,从而为英文字符中的上行字母(b,d,f,h,l)与下行字母(g,j,y)提供空间以美化显示。
 但这种美化在使用某些字体时会让字符串显得排列不整齐。如果发生这种情况,可以将includeFontPadding设为false,并将textAlignVertical设为center。
 只支持Android
 selectionColor  当文本被选中时突出显示的颜色  多种形式  只支持Android
 textAlignVertical  文本垂直对齐方式  auto、top、bottom、center  只支持Android
 textBreakStrategy  英文文本的分段策略  simple、highQuality(默认值)、balanced  只支持Android
 letterSpacing  字符间距  数字  只支持iOS
 textDecorationColor  文本装饰线条的颜色  多种形式  只支持iOS
 textDecorationStyle  文本装饰线条的风格  solid、double、dotted、dashed  只支持iOS
 writingDirection  文本方向  auto、ltr、rtl  只支持iOS

3,样式的继承

React Native 开发同 Web 开发相比,样式的继承是有区别的。
  • Web 开发中,如果网页大部分地方的字体都是 12px。我们只需要在 body 上设置字体大小是 12ox,那么页面上所有元素的默认字体大小就都是 12px
  • React Native 不支持这种继承,字体样式只有在 Text 组件上才起作用。因此字体样式的继承也只能通过 Text 组件来实现,即内部的 Text 组件可以继承外部 Text 组件的样式。
(1)效果图
下面样例中左右两个Text组件的颜色不同,但它们的字体大小、粗细都是一样的。

(2)样例代码
我们就可以在这两个 Text 的最外层再嵌套一个 Text 组件,将公共样式设置在这里。
import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
 } from 'react-native';

class Main extends Component {
   render() {
     return (
      <View style={[styles.flex, styles.container]}>
        <Text style={styles.font}>
          <Text style={styles.font1}>欢迎访问 </Text>
          <Text style={styles.font2}>hangge.com</Text>
        </Text>
      </View>
     );
   }
 }

 const styles = StyleSheet.create({
   flex:{
       flex:1
   },
   container: {
    marginTop:35,
    marginLeft:5,
    marginRight:5,
  },
  font:{
    fontSize:28,
    fontWeight:'bold',
  },
  font1:{
    color:'#FF7700',
  },
  font2:{
    color:'#2D9900',
  },
 });

 AppRegistry.registerComponent('HelloWorld', () => Main);

4,点击事件响应

Text 被点击或者按下时会调用 onPress 方法。而长按的话会调用 onLongPress 方法。
下面样例当点击 Text 组件时,弹出一个消息框。
import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
 } from 'react-native';

class Main extends Component {
   render() {
     return (
      <View style={[styles.flex, styles.container]}>
        <Text style={styles.font} onPress={this.show.bind(this, "点击了Text")}>
          欢迎访问 hangge.com
        </Text>
      </View>
     );
   }
   show(msg){
     alert(msg);
   }
 }

 const styles = StyleSheet.create({
   flex:{
       flex:1
   },
   container: {
    marginTop:35,
    marginLeft:5,
    marginRight:5,
  },
  font:{
    fontSize:28,
    fontWeight:'bold',
  },
 });

 AppRegistry.registerComponent('HelloWorld', () => Main);


5,numberOfLines属性

Text 在文字在文字过长的情况下会自动换行。我们可以通过 numberOfLines 属性来规定最多显示多少行,如果超出该数值,则以省略号(...)表示。
<Text style={styles.font} numberOfLines={1}>
  hangge.com 做最好的开发者知识平台
</Text>

6,ellipsizeMode 属性

这个通常和上面的 numberOfLines 属性配合使用,表示当 Text 组件无法全部显示需要显示的字符串时如何用省略号进行修饰。
该属性有如下 4 种取值:
  • head:头部显示省略号
  • middle:中间显示省略号
  • tail:尾部使用省略号(默认值)
  • clip:不显示省略号,尾部直接截断
<Text style={styles.font} numberOfLines={1} ellipsizeMode='middle'>
  hangge.com 做最好的开发者知识平台
</Text>


7,onLayout方法

Text 组件的布局变化时会调用 onLayout 方法。
(1)样例效果图及代码
 import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
 } from 'react-native';

class Main extends Component {
   render() {
     return (
      <View style={[styles.flex, styles.container]}>
        <Text style={styles.font} onLayout={this.textOnLayout}>
          hangge.com 做最好的开发者知识平台
        </Text>
      </View>
     );
   }
   textOnLayout(e){
    const layout = e.nativeEvent.layout;
    console.log(layout);
   }
 }

 const styles = StyleSheet.create({
   flex:{
       flex:1
   },
   container: {
    marginTop:35,
    marginLeft:5,
    marginRight:5,
  },
  font:{
    fontSize:28,
    fontWeight:'bold',
  },
 });

 AppRegistry.registerComponent('HelloWorld', () => Main);

(2)页面初始化后,打印结果如下:

8,selectable 属性

(1)这个是布尔类型的属性,默认值为:false
(2)当它为 true 时,字符串组件中的文字可以被选择并被复制到手机系统的剪贴板中。
<Text selectable={true}>
  hangge.com 做最好的开发者知识平台
</Text>

9,Text 组件的嵌套

(1)我们在开发中可以使用嵌套的 Text 组件,它们的样式遵循如下规则:
  • Text 组件将继承它的父 Text 组件的样式。
  • Text 组件只能增加父 Text 组件没有指定的样式。
  • Text 组件不能覆盖从父 Text 组件继承而来的样式。覆盖了也不会生效,并且在开发模式下会弹出警告。
(2)在嵌套 Text 组件的显示字符串中,希望重起一行显示的字符串必须要在字符串前加 {'\r\n'},否则会接着上一行末显示。
<Text style={{fontSize:20, textAlign:'center'}}>
  hangge.com
  <Text style={{fontWeight:'bold'}}>
     {'\r\n'}做最好的
    <Text style={{color:'black'}}>
      {'\r\n'}开发者知识平台
    </Text>
  </Text>
</Text>

10,文字垂直居中

(1)想要让 Text 组件内部的文字水平居中,只需要将其 textAlign 设为 center 即可。
(2)但如果想让内部的文字垂直居中,将其 justifyContent 设为 center 是没有效果的。正确的做法应该是在 Text 外再加一个包围它的 View,然后让 Text 组件在这个 View 内垂直居中。
import React, { Component } from 'react';
 import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
 } from 'react-native';

class Main extends Component {
   render() {
     return (
      <View style={[styles.flex, styles.container]}>

        <View style={styles.viewForTextStyle} >
          <Text style={styles.textStyle}>
            hangge.com
          </Text>
        </View>

      </View>
     );
   }
 }

 const styles = StyleSheet.create({
   flex:{
       flex:1
   },
   container: {
    marginTop:35,
    marginLeft:5,
    marginRight:5,
    alignItems:'center',
  },
  viewForTextStyle:{
    height:100,
    width:200,
    alignItems:'center',
    justifyContent:'center',
    backgroundColor:'orange'
  },
  textStyle:{
    color:'white',
    fontWeight:'bold',
    fontSize:26
  }
 });

 AppRegistry.registerComponent('HelloWorld', () => Main);

11,在字符串中插入图像

Text 组件除了可以用来显示文字,还可以在其内部插入图像。
注意:如果是 iOS 平台,除了可以在字符串中插入图像,还可插入一个 View,这个 View 内容由开发者自己生成。
import React, { Component } from 'react';
import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
   Image,
 } from 'react-native';

class Main extends Component {
   render() {
     var image = require('./logo.png');
     return (
      <View style={[styles.flex, styles.container]}>
        <Text style={styles.welcome}>
          欢迎访问 <Image source={image} style={styles.imageInText} /> ...
        </Text>
      </View>
     );
   }
 }

 const styles = StyleSheet.create({
    flex:{
       flex:1
    },
    container: {
      marginTop:35,
      alignItems:'center',
    },
    welcome:{
      fontSize:30
    },
    imageInText:{
      width:260,
      height:55,
      resizeMode:'cover'
    }
 });

 AppRegistry.registerComponent('HelloWorld', () => Main);

附:下面是 iOS 平台独有的属性

1,adjustsFontSizeToFit 属性

(1)这个是布尔类型的属性,默认值为:false
(2)当它为 true 时,Text 组件会自动按比例缩小字体以适应样式限制。

2,allowFontScaling 属性

(1)这个是布尔类型的属性,默认值为:true
(2)当它为 true 时,Text 组件字体会自动根据 iOS 的“文本大小”辅助选项来进行缩放。

3,minimumFontScale 属性

(1)它定义了当字体因为 adjustsFontSizeToFit 生效而按比例缩小时,字体的最小缩小比例。
(2)取值范围:0.01 ~ 1.0

4,suppressHighlighting 属性

这个是布尔类型的属性,默认值为:false
  • 当它为 false 时,Text 组件被按下后,会被突出显示为一个灰色椭圆背景组件。
  • 当它为 true 时,Text 组件被按下后不会有任何视觉上的变化。
注意:这个属性只有 Text 组件设置了 onPress 属性或者 onLongPress 属性时才会生效。
评论

全部评论(0)

回到顶部