英文:
Proper way to render a series of HTML tags with the "for in" loop in React
问题
以下是代码的翻译部分:
这是我的代码的精简版本。我认为你可以理解我想要做的事情,但只显示了名字。有人可以向我展示在React中正确的做法吗?
import "./styles.css";
import { useState } from "react";
export default function App() {
const [annie, renameAnnie] = useState({
firstname: "Annie",
middlename: "Rose",
lastname: "Markham"
});
const fullName = () => {
for (let x in annie) {
return (
<span>{annie[x]}</span>
)
}
};
return (
<>
{fullName()}
</>
);
}
请注意,上述翻译只包括代码部分,不包括问题或其他内容。如果您需要进一步的帮助或有其他问题,请随时提出。
英文:
Here's a condensed version of my code. I think you can get what I'm trying to do, but only the first name displays. Can anyone show me the proper way to do this in React?
import "./styles.css";
import { useState } from "react";
export default function App() {
const [annie, renameAnnie] = useState({
firstname: "Annie",
middlename: "Rose",
lastname: "Markham"
});
const fullName = () => {
for (let x in annie) {
return(
<span>{annie[x]}</span>
)
}
};
return (
<>
{fullName()}
</>
);
}
答案1
得分: 1
这不起作用,因为在第一次迭代中只会返回单个<span>
。相反,尝试以下代码:
return (
<>
{Object.values(annie).map((item, index) => (
<span key={index}>{item}</span>
))}
</>
)
基本上,使用Array.prototype.map(),我们可以构建一个新数组,其中每个元素都由对annie
的值应用的函数产生。您可以将其视为编写以下更简洁方式的方法:
const results = []
const values = Object.values(annie)
for (let i = 0; i < values.length; i++) {
results.append(<span key={i}>{values[i]}</span>)
}
return <>{results}</>
英文:
This does not work because the single <span>
will be returned on the first iteration. Instead, try
return (
<>
{Object.values(annie).map((item, index) => (
<span key={index}>{item}</span>
))}
</>
)
Essentially, using Array.prototype.map() we can construct a new array where each element is yielded by a function on the values of annie
. You can think of it as a more concise way to write the following:
const results = []
const values = Object.values(annie)
for (let i = 0; i < values.length; i++) {
results.append(<span key={i}>{values[i]}</span>)
}
return <>{results}</>
答案2
得分: 1
只有第一个名字显示,这是因为 for
循环内部的 return
语句导致的。
另一种方法是将 fullName
函数返回 annie
对象的 span
数组,使用 Object.values(),然后可以在 JSX 中显示它:
const fullName = () => {
return Object.values(annie).map((value, index) => (
<span key={index}>{value}</span>
));
};
英文:
> but only the first name displays
This is because of the return
statement inside the for
loop.
an alternative is to make the fullName
function returning an array of span
from the annie
object using Object.values(), then this can be displayed within the JSX :
const fullName = () => {
return Object.values(annie).map((value, index) => (
<span key={index}>{value}</span>
));
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论