7

设置

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

问题

Text 组件中的断字不会按照应用程序设计的方式处理带有破折号的字符串。我想考虑破折号来换行整个单词。换行时,应将整个带有破折号的字符串视为一个单词。但 flexbox 没有。

代码

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

结果看起来像这样:

在此处输入图像描述

但我希望它以这样的方式结束(text-with-dash在单独的行上):

在此处输入图像描述

问题是我从在线 CMS 中获取字符串,并且想要一个 flexbox 样式解决方案来解决这个问题。在某些情况下,带破折号的字符串可能会出现在一行中,因此在这些情况下,我不想要原因的自动换行。

4

3 回答 3

4

\u2011在字符串中使用不间断连字符的unicode 。因此,对于您的示例,它看起来像这样:

<TouchableOpacity style={{ width: 250, backgroundColor: 'skyblue' }}>
    <Text style={styles.welcome}>{`This is a sample of text\u2011with\u2011dash incorrectly word breaking`}</Text>
</TouchableOpacity>
于 2020-10-12T13:50:30.300 回答
2

您现在可以使用textbreakstrategy作为Text的道具。

默认情况下,文本中断策略是“ highQuality ”,它会中断单词并为这些单词附加“-”。

在 textbreakstrategy 中使用 ' simple ' 来避免分词时出现 '-'。

例如:

<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

于 2019-05-28T04:38:52.730 回答
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>
          );
           }
         }
于 2018-11-14T17:33:23.037 回答