将 HTML 存储在一个变量中,以便以后在 Next JS 中使用
Storing HTML in a variable for later use in Next JS
在 Next JS 中,我的代码看起来像这样:
function Test() {
return (
<section>
<div>Test</div>
</section>
);
}
但是假设我想在这里有多个条目,由代码生成。我基本上想用预先计算的 HTML 替换 <section>
的内容。这是我尝试过的:
function Test() {
let posts;
for (let i = 0; i < 3; i += 1) {
posts += <div>Test</div>;
}
return (
<section>{posts}</section>
);
}
但是,这只会产生输出 [object Object][object Object][object Object]
,这不是我想要的。我试过用引号和坟墓围绕 HTML,但它不起作用。我真的不知道我应该怎么做才能完成这项工作。
+
仅连接字符串;您需要使用 .push()
或 .map()
将元素对象存储在数组中。调用时会打印出整个数组的内容。
此代码有效:
function Test() {
const posts = [];
for (let i = 0; i < 3; i += 1) {
posts.push(<div>Test</div>);
}
return (
<section>{posts}</section>
);
}
在 Next JS 中,我的代码看起来像这样:
function Test() {
return (
<section>
<div>Test</div>
</section>
);
}
但是假设我想在这里有多个条目,由代码生成。我基本上想用预先计算的 HTML 替换 <section>
的内容。这是我尝试过的:
function Test() {
let posts;
for (let i = 0; i < 3; i += 1) {
posts += <div>Test</div>;
}
return (
<section>{posts}</section>
);
}
但是,这只会产生输出 [object Object][object Object][object Object]
,这不是我想要的。我试过用引号和坟墓围绕 HTML,但它不起作用。我真的不知道我应该怎么做才能完成这项工作。
+
仅连接字符串;您需要使用 .push()
或 .map()
将元素对象存储在数组中。调用时会打印出整个数组的内容。
此代码有效:
function Test() {
const posts = [];
for (let i = 0; i < 3; i += 1) {
posts.push(<div>Test</div>);
}
return (
<section>{posts}</section>
);
}