2017-06-20 27 views
0

我在數組中保存了更多的字符串。我想要做的就是將它們分別放在不同的圖標上時將它們顯示出來。 我試了一下,到目前爲止:在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 

」不是個t <hr/>在這種情況下必須使用什麼?謝謝

+1

聽起來你正在尋找''
我 –

+0

還試圖與但我想的是,它不能識別標籤,它需要像純文本 –

+0

showWhenHover全部返回一個文本節點。如果你將它渲染爲標記,你想返回一個React.Component實例。 –

回答

1

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

+0

它使它更好,但不是它必須如此。我的意思是,如果數組's1'和's2'中有2個字符串,則顯示s1s2


s1s2。它有3個字符串,它顯示s1s2s3
s1s2s3
。我希望我的解釋清楚, –

+0

解決了它。它必須在span中使用'text [index]'而不是'text'。 –

+0

對不起,這是我的錯誤,我將參數重命名爲'item'以使其更清晰,因此您不需要使用文本[index]。 – glennreyes

0

你的函數addMessage生成字符串而不是html標記。

一個解決方案是使用模板文字允許multiline strings。另一件事是確保文本包含在已定義尺寸的元素中,或者尺寸足夠大以便文本可以進入下一行。

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>

0

您還可以使用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>