用破折号反应字符串的本机文本分词策略

时间:2018-11-13 11:30:16

标签: react-native text flexbox word-wrap text-styling

设置

react: 16.6.0-alpha.8af6728
react-native: 0.57.4

问题

“文本”组件中的断字功能无法按照应用程序设计的方式使用破折号处理字符串。我想对整个单词进行自动换行,并考虑破折号。换行时,应将整个带破折号的字符串视为一个单词。但是flexbox不会。

代码

<TouchableOpacity style={{ width: 250, backgroundColor: 'skyblue' }}>
    <Text style={styles.welcome}>This is a sample of text-with-dash incorrectly word breaking</Text>
</TouchableOpacity>

Restult看起来像这样:

enter image description here

但是我希望它以这样的方式结束(带短划线的文本):

enter image description here

问题是我从在线CMS获取字符串,并希望使用Flexbox样式解决方案来解决此问题。可能会有带破折号的字符串以单行结尾的情况,因此在这些情况下,我不需要原因的自动换行。

3 个答案:

答案 0 :(得分:0)

找不到任何CSS技巧。但是您可以使用regx作为快捷方式。只需在任何带连字符的单词之前添加新行。这不是一个完美的解决方案,但至少对于这种情况,它会起作用

        export default class App extends Component {
        constructor(props) {
        super(props);

         this.processString = this.processString.bind(this);
        }

         processString() {
         const regex = /((\w+\-(.*?)\w+)\s)/gm;
         const str = `This is a sample of text-with-dash incorrectly word breaking`;
         const subst = `\n$1`;
         const result = str.replace(regex, subst);
         return result;
        }

         render() {
             return (
                  <View style={styles.container}>
          <TouchableOpacity style={{ width: 250, backgroundColor: 
        "skyblue" 
         }}>
          <Text style={styles.welcome}>{this.processString()}</Text>
           </TouchableOpacity>
          </View>
          );
           }
         }

答案 1 :(得分:0)

您现在可以将textbreakstrategy用作文本的道具。

默认情况下,文本拆分策略为' highQuality ',它会拆分单词并为这些单词附加'-'。

在文本中断策略中使用“ 简单”来避免在打断单词时使用“-”。

例如:

<Text textBreakStrategy={'simple'}>
This is a sample of text-with-dash incorrectly word breaking
</Text>

其他参考: https://developer.android.com/reference/android/text/Layout.html#BREAK_STRATEGY_SIMPLE

答案 2 :(得分:0)

在字符串中使用non breaking hyphen中的Unicode \u2011。因此,对于您的示例,它看起来像这样:

<TouchableOpacity style={{ width: 250, backgroundColor: 'skyblue' }}>
    <Text style={styles.welcome}>{`This is a sample of text\u2011with\u2011dash incorrectly word breaking`}</Text>
</TouchableOpacity>