文本

2019-08-14 14:23 更新

用于顯示文本的響應(yīng)組件,支持嵌套、樣式和觸發(fā)處理。在接下來(lái)的例子中,嵌套的標(biāo)題和正文文本將從styles.baseText 繼承 FontFamily,但是標(biāo)題會(huì)提供它自己其他的設(shè)計(jì)風(fēng)格。標(biāo)題和正文在文字換行時(shí)會(huì)堆疊在彼此之上。

renderText: function() {
  return (    <Text style={styles.baseText}>
      <Text style={styles.titleText} onPress={this.onPressTitle}>
        {this.state.titleText + '\n\n'}      </Text>
      <Text numberOfLines={5}>
        {this.state.bodyText}      </Text>
    </Text>
  );
},
...
var styles = StyleSheet.create({
  baseText: {
    fontFamily: 'Cochin',
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
  },
};

Props

Edit on GitHub

numberOfLines 數(shù)值型

用于在計(jì)算文本布局后將文本和省略符號(hào)進(jìn)行截?cái)?,包括換行,這樣總的行數(shù)就不會(huì)超過(guò)這個(gè)值。

onPress 函數(shù)

這個(gè)函數(shù)被稱為按下。在默認(rèn)高亮狀態(tài)下,文本內(nèi)部是支持按下動(dòng)作處理的(該函數(shù)在 suppressHighlighting 是禁用的)。

style style

View#style...

color 字符串型

containerBackgroundColor 字符串型

fontFamily 字符串型

fontSize 數(shù)值型

fontStyle enum('normal', 'italic')

fontWeight enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900')

lineHeight 數(shù)值型

textAlign enum("auto", 'left', 'right', 'center')

writingDirection enum("auto", 'ltr', 'rtl')

suppressHighlighting 布爾型

值為真時(shí),當(dāng)文本被按下時(shí)沒(méi)有視覺(jué)上的變化。默認(rèn)情況下,按下之前是一個(gè)灰色橢圓高亮的文本。

testID 字符串型

在端到端測(cè)試時(shí)用于定位視圖

描述

Edit on GitHub

嵌套文本

在 iOS 里,顯示格式化文本的方式是使用 NSAttributedString :你可以為你想要顯示和注釋的文本劃定一些特定的格式范圍。實(shí)際上,這是非常無(wú)聊的。對(duì)于 React Native,我們決定使用 Web 模式,在這里我們可以利用嵌套文本來(lái)達(dá)到同樣的效果。

    <Text style={{fontWeight: 'bold'}}>
      I am bold      <Text style={{color: 'red'}}>
        and red      </Text>
    </Text>

在幕后,這將會(huì)被轉(zhuǎn)換成一個(gè)完全的包含以下信息的 NSAttributedString

    "I am bold and red"
    0-9: bold    9-17: bold, red

容器

<Text> 元素是與布局設(shè)計(jì)有特定關(guān)系的:內(nèi)部的一切都不再使用 flexbox 布局而是使用文本布局。這意味著一個(gè)<Text> 內(nèi)部的元素不在是矩形的,而是在結(jié)尾的時(shí)候被包裝起來(lái)。

    <Text>
      <Text>First part and </Text>
      <Text>second part</Text>
    </Text>
    // Text container: all the text flows as if it was one
    // |First part |
    // |and second |
    // |part       |    <View>
      <Text>First part and </Text>
      <Text>second part</Text>
    </View>
    // View container: each text is its own block
    // |First part |
    // |and        |
    // |second part|

有限制性的樣式繼承

在網(wǎng)絡(luò)上,為整個(gè)文檔設(shè)置字體體系和大小的常用方法是:

    /* CSS, *not* React Native */
    html {      font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;      font-size: 11px;      color: #141823;
    }

當(dāng)瀏覽器想要顯示一個(gè)文本節(jié)點(diǎn)時(shí),它會(huì)一直走到樹(shù)的根元素,并且找到一個(gè)有 font-size屬性的元素。該系統(tǒng)一個(gè)意想不到的性質(zhì)是任何節(jié)點(diǎn)都可以有font-size屬性,包括一個(gè) <div>。這是為了方便而設(shè)計(jì)的,盡管語(yǔ)義并不是正確的。

在 React Naitve 里,我們關(guān)于這一點(diǎn)會(huì)更嚴(yán)格:你必須將 <Text> 組件里的所有節(jié)點(diǎn)都進(jìn)行包裝;你不能在 <View>下直接擁有一個(gè)文本節(jié)點(diǎn)。

    // BAD: will fatal, can't have a text node as child of a <View>
    <View>
      Some text    </View>
    // GOOD    <View>
      <Text>
        Some text       </Text>
    </View>

你也失去了對(duì)整個(gè)子樹(shù)設(shè)置字體的能力。為了在你的應(yīng)用程序里使用一致為字體和大小,推薦使用的方法是創(chuàng)建一個(gè)包括他們的 MyAppText 組件,并且在你的應(yīng)用程序里使用這個(gè)組件。你可以使用該組件來(lái)構(gòu)成更多特定的組件,比如用于其他類型文本的 MyAppHeaderText 組件。

    <View>
      <MyAppText>Text styled with the default font for the entire application</MyAppText>
      <MyAppHeaderText>Text styled as a header</MyAppHeaderText>
    </View>

React Native 還有繼承風(fēng)格的概念,但是僅限于文本子樹(shù)。在這種情況下,第二部分將是粗體和紅色。

    <Text style={{fontWeight: 'bold'}}>
      I am bold      <Text style={{color: 'red'}}>
        and red      </Text>
    </Text>

我們相信更多的文本約束方法將會(huì)產(chǎn)生更好的應(yīng)用程序:

  • (開(kāi)發(fā)人員)響應(yīng)組件的設(shè)計(jì)源于大腦中孤立的想法:你應(yīng)該有能力將你的組件放置在你應(yīng)用程序的任何一個(gè)地方,相信只有工具是相同的,那么它的表現(xiàn)和行為都是相同的。文本屬性是可以從工具外繼承的,這會(huì)打破這種孤立。

  • (實(shí)現(xiàn)人員)React Native 實(shí)現(xiàn)也是很簡(jiǎn)單的。我們不需要對(duì)每一個(gè)單一的元素都要有一個(gè) FontFamily 模塊,并且我們?cè)诿恳淮物@示一個(gè)文本節(jié)點(diǎn)時(shí)也不需要對(duì)樹(shù)遍歷到根節(jié)點(diǎn)。風(fēng)格的繼承只需要在原生文本內(nèi)部進(jìn)行編碼,不需要泄露給其他文本或者是系統(tǒng)本身。

例子

Edit on GitHub

'use strict';var React = require('react-native');var {
  StyleSheet,
  Text,
  View,
} = React;var Entity = React.createClass({
  render: function() {    return (
      <Text style={styles.entity}>
        {this.props.children}
      </Text>
    );
  }
});var AttributeToggler = React.createClass({
  getInitialState: function() {    return {fontWeight: '500', fontSize: 15};
  },
  increaseSize: function() {
    this.setState({
      fontSize: this.state.fontSize + 1
    });
  },
  render: function() {    var curStyle = {fontSize: this.state.fontSize};    return (
      <Text>
        <Text style={curStyle}>
          Tap the controls below to change attributes.
        </Text>
        <Text>
          See how it will even work on{' '}
          <Text style={curStyle}>
            this nested text
          </Text>
          <Text onPress={this.increaseSize}>
            {'>> Increase Size <<'}
          </Text>
        </Text>
      </Text>
    );
  }
});
exports.title = '<Text>';
exports.description = 'Base component for rendering styled text.';
exports.displayName = 'TextExample';
exports.examples = [
{
  title: 'Wrap',
  render: function() {    return (
      <Text>
        The text should wrap if it goes on multiple lines. See, this is going to
        the next line.
      </Text>
    );
  },
}, {
  title: 'Padding',
  render: function() {    return (
      <Text style={{padding: 10}}>
        This text is indented by 10px padding on all sides.
      </Text>
    );
  },
}, {
  title: 'Font Family',
  render: function() {    return (
      <View>
        <Text style={{fontFamily: 'Cochin'}}>
          Cochin
        </Text>
        <Text style={{fontFamily: 'Cochin', fontWeight: 'bold'}}>
          Cochin bold
        </Text>
        <Text style={{fontFamily: 'Helvetica'}}>
          Helvetica
        </Text>
        <Text style={{fontFamily: 'Helvetica', fontWeight: 'bold'}}>
          Helvetica bold
        </Text>
        <Text style={{fontFamily: 'Verdana'}}>
          Verdana
        </Text>
        <Text style={{fontFamily: 'Verdana', fontWeight: 'bold'}}>
          Verdana bold
        </Text>
      </View>
    );
  },
}, {
  title: 'Font Size',
  render: function() {    return (
      <View>
        <Text style={{fontSize: 23}}>
          Size 23
        </Text>
        <Text style={{fontSize: 8}}>
          Size 8
        </Text>
      </View>
    );
  },
}, {
  title: 'Color',
  render: function() {    return (
      <View>
        <Text style={{color: 'red'}}>
          Red color
        </Text>
        <Text style={{color: 'blue'}}>
          Blue color
        </Text>
      </View>
    );
  },
}, {
  title: 'Font Weight',
  render: function() {    return (
      <View>
        <Text style={{fontWeight: '100'}}>
          Move fast and be ultralight
        </Text>
        <Text style={{fontWeight: '200'}}>
          Move fast and be light
        </Text>
        <Text style={{fontWeight: 'normal'}}>
          Move fast and be normal
        </Text>
        <Text style={{fontWeight: 'bold'}}>
          Move fast and be bold
        </Text>
        <Text style={{fontWeight: '900'}}>
          Move fast and be ultrabold
        </Text>
      </View>
    );
  },
},  {
  title: 'Font Style',
  render: function() {    return (
      <View>
        <Text style={{fontStyle: 'normal'}}>
          Normal text
        </Text>
        <Text style={{fontStyle: 'italic'}}>
          Italic text
        </Text>
      </View>
    );
  },
}, {
  title: 'Nested',
  description: 'Nested text components will inherit the styles of their ' +    'parents (only backgroundColor is inherited from non-Text parents).  ' +    '<Text> only supports other <Text> and raw text (strings) as children.',
  render: function() {    return (
      <View>
        <Text>
          (Normal text,
          <Text style={{fontWeight: 'bold'}}>
            (and bold
            <Text style={{fontSize: 11, color: '#527fe4'}}>
              (and tiny inherited bold blue)
            </Text>
            )
          </Text>
          )
        </Text>
        <Text style={{fontSize: 12}}>
          <Entity>Entity Name</Entity>
        </Text>
      </View>
    );
  },
}, {
  title: 'Text Align',
  render: function() {    return (
      <View>
        <Text style={{textAlign: 'left'}}>
          left left left left left left left left left left left left left left left
        </Text>
        <Text style={{textAlign: 'center'}}>
          center center center center center center center center center center center
        </Text>
        <Text style={{textAlign: 'right'}}>
          right right right right right right right right right right right right right
        </Text>
      </View>
    );
  },
}, {
  title: 'Spaces',
  render: function() {    return (
      <Text>
        A {'generated'} {' '} {'string'} and    some &nbsp;&nbsp;&nbsp; spaces
      </Text>
    );
  },
}, {
  title: 'Line Height',
  render: function() {    return (
      <Text>
        <Text style={{lineHeight: 35}}>
          A lot of space between the lines of this long passage that should
          wrap once.
        </Text>
      </Text>
    );
  },
}, {
  title: 'Empty Text',
  description: 'It\'s ok to have Text with zero or null children.',
  render: function() {    return (
      <Text />
    );
  },
}, {
  title: 'Toggling Attributes',
  render: function(): ReactElement {    return <AttributeToggler />;
  },
}, {
  title: 'backgroundColor attribute',
  description: 'backgroundColor is inherited from all types of views.',
  render: function() {    return (
      <View style={{backgroundColor: 'yellow'}}>
        <Text>
          Yellow background inherited from View parent,
          <Text style={{backgroundColor: '#ffaaaa'}}>
            {' '}red background,
            <Text style={{backgroundColor: '#aaaaff'}}>
              {' '}blue background,
              <Text>
                {' '}inherited blue background,
                <Text style={{backgroundColor: '#aaffaa'}}>
                  {' '}nested green background.
                </Text>
              </Text>
            </Text>
          </Text>
        </Text>
      </View>
    );
  },
}, {
  title: 'containerBackgroundColor attribute',
  render: function() {    return (
      <View>
        <View style={{flexDirection: 'row', height: 85}}>
          <View style={{backgroundColor: '#ffaaaa', width: 150}} />
          <View style={{backgroundColor: '#aaaaff', width: 150}} />
        </View>
        <Text style={[styles.backgroundColorText, {top: -80}]}>          Default containerBackgroundColor (inherited) + backgroundColor wash
        </Text>
        <Text style={[
          styles.backgroundColorText,
          {top: -70, containerBackgroundColor: 'transparent'}]}>
          {"containerBackgroundColor: 'transparent' + backgroundColor wash"}
        </Text>
      </View>
    );
  },
}, {
  title: 'numberOfLines attribute',
  render: function() {    return (
      <View>
        <Text numberOfLines={1}>
          Maximum of one line no matter now much I write here. If I keep writing it{"'"}ll just truncate after one line
        </Text>
        <Text numberOfLines={2} style={{marginTop: 20}}>
          Maximum of two lines no matter now much I write here. If I keep writing it{"'"}ll just truncate after two lines
        </Text>
        <Text style={{marginTop: 20}}>
          No maximum lines specified no matter now much I write here. If I keep writing it{"'"}ll just keep going and going
        </Text>
      </View>
    );
  },
}];var styles = StyleSheet.create({
  backgroundColorText: {
    left: 5,
    backgroundColor: 'rgba(100, 100, 100, 0.3)'
  },
  entity: {
    fontWeight: '500',
    color: '#527fe4',
  },
});


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)