React Native适合文本组件

时间:2018-04-21 22:27:29

标签: javascript react-native fonts flexbox expo

我试图将我的文字放在可用区域内,我的约束是这样的:

  • 文字不应该溢出,
  • 文字必须在所有可用视图中扩展,
  • 单词不应该分成字符并转到下一行句子,
  • 当我在父视图中使用flex时,文本不应该横向扩展视图宽度以上。

这是我的代码段:

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { Font } from "expo";
import Lorem from "./src/helpers/lorem-ipsum-gen";

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {
      fontLoaded: false,
    };
  }
  //theboldfont.ttf
  async componentWillMount() {
    await Font.loadAsync({
      "akzidenz-grotesk-bq-bold": require("./assets/fonts/AkzidenzGrotesk_BQ_Bold.otf"),
    });
    this.setState({ fontLoaded: true });
  }

  render() {
    let loremText = new Lorem().generate(20)

    return (
      <View style={styles.container}>
        <View>
          <View style={{ flex: 0.37 }} > </View>
          <View style={{ flex: 0.25, backgroundColor: "red" }} >
            <View >
              {
                this.state.fontLoaded ? (<Text
                  style={{ fontFamily: "akzidenz-grotesk-bq-bold", fontSize: 50 }}
                  adjustsFontSizeToFit={true}
                >
                  {loremText}
                </Text>) : null
              }

            </View>
          </View>
          <View style={{ flex: 0.38 }} >
            <Text>
              {loremText}
            </Text>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

结果:

sample screenshot

我尝试实现目标:

  • 我认为它与自定义字体&amp;更改为默认字体(未使用)
  • 在一些github问题中,人们在文本样式支柱中写了adjustsFontSizeToFit = {true}(不工作)
  • 我尝试过allowFontScaling(Not working)
  • 删除了fontsize(不可用)
  • 删除了flex并设置静态宽度和高度以查看(Not working)
  • 上述所有步骤的组合(不起作用)

2 个答案:

答案 0 :(得分:1)

因此,在对文本组件尝试新内容之后,我发现adjustsFontSizeToFit={true}在没有指定numberOfLines={number}的情况下无法正常工作,但它有时会将我的单词划分为字符末尾的字符。从文档可能它在Android中不可用。所以我仍然需要一种更好的方法来找到问题的解决方案

答案 1 :(得分:0)

注意:此解决方案需要反复试验,并采用固定大小的容器。

您可以使用interpolation函数根据最长行的长度缩小文本。

插值函数示例(随意使用我的interpolation function):

const fontSizeInterpolator = Interpolator.getInterpolator({
    input:  [4,  5,  6,  7,  8,  10, 11, 13, 40],
    output: [45, 45, 32, 28, 28, 22, 19, 15, 10]
});

这意味着如果最长的行是四个字符长,请将字体大小设置得很大。如果最长的行是40个字符,请将字体大小设置得很小。通过反复试验,将特定的行长映射到特定的字体大小。

通过常规逻辑找到文本中最长的一行(这里我每行只有一个单词):

const words = props.text.split(' ');
let longestWord = words[0];
for (const word of words) {
  if (word.length > longestWord.length) {
    longestWord = word;
  }
}

然后从插值器获取字体大小:

const fontSize = fontSizeInterpolator(longestWord.length);

示例输出:

example output