繁体   English   中英

在React中将文本分成多行

[英]Break a text into multiple lines in React

我将更多的字符串保存在数组中。 我要做的是将鼠标悬停在图标上时,分别显示在单独的行上,以显示它们。 到目前为止我尝试过的是:

addMessages = () => {
   const text = [];

   //add strings in the array

   return text.join("<hr/>");

}

render() {
   const showWhenHover = this.addMessages();

   return (
            <ActionBar popover={<div> {showWhenHover}</div>}
               <div>
                   <Icon type="myIcon"/>
               </div>
           </ActionBar>
          );
      }
}

当我将鼠标悬停在图标上时,它将显示消息,但不是每行都显示在一条消息中,而是全部显示在一行中,如下所示:

text1</hr>text2</hr>text3

<hr/>在这种情况下不是必须使用吗? 谢谢

text.join将呈现单个字符串,在这种情况下,包括<hr /> 为了呈现JSX,请尝试:

addMessages = () => {
  const text = [];

  // add strings in the array

  return text.map((item, index) => (
    <span key={index}>
      {item}
      {index && <hr />}
    </span>
  ));
}

唯一的缺点是额外的跨度,但我宁愿使用此方法而不是使用dangerouslySetInnerHTML

您的函数addMessage生成字符串,而不是html标记。

一种解决方案是使用模板文字允许多行字符串 另一件事是,确保文本包含在已定义尺寸的元素内,或者尺寸足够大以使文本可以转到下一行。

 const genText = () => ` Text with lots of spaces within it blah blah blah blah ` const Comp = () => <div style={{width: 100, height: 200}}>{genText()}</div> ReactDOM.render(<Comp />, document.getElementById('app')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

您还可以使用return text.map(e => <div>{e}</div>); 将每个字符串放在自己的行中。

 function addMessages() { const text = []; text.push("1st line"); text.push("2nd line"); text.push("Third line"); text.push("And a final one"); return text.map(e => <div>{e}</div>); } const App = () => <div>{addMessages()}</div> ReactDOM.render(<App />, document.getElementById('app')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM