我有一個包含換行符的字串。例如:
const myString = `hello\nstring`
然后我試圖在一個功能組件中使用這個字串,該組件被包裹在一個p標簽周圍。例如:
export default function App() {
const testString = "hi\nString";
return (
<div className="App">
<p>{testString}</p>
</div>
);
}
出于某種原因,p當我希望它跨兩行顯示時,該標簽只是在一行上顯示“hello string”。有沒有辦法阻止p標簽從字串中洗掉換行符?
以下代碼沙箱包含可執行示例:https ://codesandbox.io/s/unruffled-allen-ehrsd8?file=/src/App.js
uj5u.com熱心網友回復:
我認為這是因為默認情況下瀏覽器中會折疊新行和空格。您不需要任何 JavaScript,只需在樣式表中添加以下行 -
p {
white-space: pre-wrap;
}
uj5u.com熱心網友回復:
您可以在代碼中找到.split任何時候使用方法\n來輸入新行
function NewlineText(props) {
const text = props.text;
const newText = text.split('\n').map(str => <p>{str}</p>);
return newText;
}
export default function App() {
const testString = `hi\nString`;
return (
<div className="App">
<p><NewlineText text={testString} /></p>
</div>
);
}
該網站可能會清除您的任何疑慮。
uj5u.com熱心網友回復:
您是否使用<br/>代碼來斷線。?請檢查下面給出的代碼 -
export default function App() {
const testString = "hi<br/>String";
return (
<div className="App">
<p>{testString}</p>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450910.html
標籤:javascript html 反应
下一篇:如何從JSON檔案中洗掉物件?
