React Native文本换行策略:带有连字符的字符串

9

安装设置

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>

结果看起来像这样:

enter image description here

但我希望它最终呈现为这样(text-with-dash 单独一行):

enter image description here

问题在于我从在线CMS获取字符串,并希望使用flexbox样式解决此问题。可能会出现带连字符的字符串单独一行的情况,因此在这些情况下,我不希望换行。
3个回答

4

在字符串中使用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>

3
您现在可以将 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

该文档提供了如何使用BREAK_STRATEGY_SIMPLE属性改进Android中文本布局的指南。此属性可以帮助您更好地控制文本在屏幕上的显示方式,从而使文本更易读和易懂。请参考上面提供的链接以获取更多信息。

2
这仅适用于Android,正如链接所描述的那样。 - gabe

0

没有找到任何与CSS相关的技巧,但您可以使用正则表达式进行快捷操作。只需在任何连字符单词之前添加一个新行即可。这不是完美的解决方案,但至少对于这种情况,它可以起作用。

        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>
          );
           }
         }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接