简体   繁体   English

React - 添加换行符;

[英]React - Adding a line break;

So I have a function for adding a line break every 60 characters.所以我有一个每 60 个字符添加一个换行符的功能。 Now what I don't understand is why the \\n doesnt work.现在我不明白的是为什么 \\n 不起作用。

function countStr (str1){
    let str2="";
    let charCount=0;
    for(let i=0; i<str.length; i++){
            if(i%60===0){
            str2=str2.concat(str1.substring(charCount,i));
            str2+="\n";
            charCount=i;
            
        }
    }
    return str2;
}


const About = () =>{
 
    return(

        <div className="about">
         <h2>I'm Gal</h2>
         <p>{changedStr}

</p>
        </div>

    );
}
export default About;

Loop over the input string.循环输入字符串。 If the current iteration is at i % 20 (and also not zero) add a line-break.如果当前迭代是在i % 20 (并且也不是零)添加换行符。 Add the character from the input string.添加输入字符串中的字符。

In your component that's rendering the string you need to add some CSS to that element so it prints properly: white-space: pre-line .在渲染字符串的组件中,您需要向该元素添加一些 CSS 以使其正确打印: white-space: pre-line

 function countStr(str) { let out = ''; for (let i = 0; i < str.length; i++) { if (i % 20 === 0 && i !== 0) out += '\\n'; out += str[i]; } return out; } // Example string of 220 characters let str = ''; for (let i = 0; i < 220; i++) { str += '1'; } function Example({ str }) { return ( <div>{str}</div> ); }; ReactDOM.render( <Example str={countStr(str)} />, document.getElementById('react') );
 div { white-space: pre-line; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

Use this simple function使用这个简单的功能

function countStr(str) {
  let str2 = '';
  while (str.length > 0) {
    str2 += str.substring(0, 60) + '\n';
    str = str.substring(60);
  }
  return str2;
}

如果你在 React 中使用它并且它正在访问网络,那是因为你可能需要一个<br/>而不是 \\n

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

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