javascript - React - 添加换行符;
问题描述
所以我有一个功能可以每 60 个字符添加一个换行符。现在我不明白为什么 \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;
解决方案
循环输入字符串。如果当前迭代在i % 20
(也不为零)添加换行符。添加输入字符串中的字符。
在渲染字符串的组件中,您需要向该元素添加一些 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>
推荐阅读
- dns - 仅在 Windows 2012 R2 上的 DNS 解析失败
- c++ - 什么是只调用一次的控制台应用程序,其参数称为
- docker - docker-compose-maven-plugin 未能执行目标
- c# - 如何在 C# 中创建 TensorProto,方法与 Python 相同
- python - 如何构建面向对象的 Python 3 项目及其导入?
- firebase - 使用 .where() 更新 Firebase 数组。但是,得到错误“.update 不是一个函数
- node.js - 使用 Nodejs 实现 Credhub
- java - spring框架spring-data-redis序列化异常
- powershell - 将有空格的字符串值传递给另一个powershell文件
- sql - 使用 case when 时的 SQL (Redshift) 错误 - 不支持这种类型的相关子查询模式