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

hds*_*evi 5 text text-styling word-wrap flexbox react-native

设置

react: 16.6.0-alpha.8af6728
react-native: 0.57.4
Run Code Online (Sandbox Code Playgroud)

问题

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>
Run Code Online (Sandbox Code Playgroud)

Restult 看起来像这样:

在此处输入图片说明

但我希望它像这样结束(文本带破折号在单独的行上):

在此处输入图片说明

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

Sad*_*han 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>
          );
           }
         }
Run Code Online (Sandbox Code Playgroud)