【问题标题】:Force line break after first word in a div in React component在 React 组件中的 div 中的第一个单词后强制换行
【发布时间】:2020-09-20 17:34:58
【问题描述】:

我正在使用<div>,其中数据来自外部来源的简单文本。例如 <div>Business in three different continents.</div> 。现在我需要显示如下文本:

         Business

in four different countries

必须有: text-align: center; 和换行符始终仅在第一个单词之后。

问题 因为我只有一个HTML element 和<div> 一起工作,所以我不能在<div> 内容中添加\n。如果我使用伪元素&::before/&::after(对于我正在使用的@emotion/styled)而不是在第一个单词之后,这只会在整行文本之后或之前。由于CSS 无法计算字数,因此仅使用CSS 似乎无法解决此问题。此外<div> 容器width 必须调整到第二行,因此我不能使用display:block,因为它将应用于整行文本。在其他帖子中看到添加两个空格以强制换行,但这不能在第一个单词之后完成,因为我没有任何嵌套的 HTML element,比如 <div><span></span></div>

顺便说一句,react-markdown 可以帮忙吗?

解决此问题的最佳方法是什么?

【问题讨论】:

    标签: javascript html css reactjs styled-components


    【解决方案1】:

    为什么不用JS把字符串分成两部分呢?

    var sentence = "Business in three different continents.";
    var firstWhiteSpace = sentence.indexOf(" ");
    var firstWord = sentence.substr(0, firstWhiteSpace);
    var restOfSentence = sentence.substr(firstWhiteSpace+1);
    
    // Then you can use different divs for the first word and the rest of the 
    // sentence and style then individually.
    <div>firstWord</div>
    <div>restOfSentence</div>
    

    【讨论】:

      【解决方案2】:

      我建议的解决方案是:

      class App extends Component {
        constructor() {
          super();
          this.state = {
            name: 'Business in three different continents.'
          };
        }
        componentDidMount(){
          let first=this.state.name.split(" ")[0];
          this.setState({
            name: first+"\n"+this.state.name.replace(first,'')
          });
        }
        render() {
          return (
            <div class="new-line">
            {this.state.name}
            </div>
          );
        }
      }
      

      在 CSS 样式中:

      .new-line {
        white-space: pre-line;
        text-align: center;
      }
      

      Working stackblitz

      如果有帮助请告诉我

      【讨论】:

        猜你喜欢
        • 2011-03-04
        • 2015-05-13
        • 2010-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多