我正在为一组页脚链接映射一小块项目对象,并且我希望每个项目名称后跟一个 |除了最后一个。这是代码。
const projects = [
{
lastOne: false,
project: "Kuma",
link: "",
image: "./kuma.png",
},
{
lastOne: false,
project: "Rin Starseed",
link: "",
image: "./star.png",
},
{
lastOne: true,
project: "Sea Harvest",
link: "",
image: "./fish.png",
},
];
然后是footer组件中的逻辑
function ProjectLinks({ link, project, lastOne }) {
return (
<a href={link} target="_blank" style={{ color: "white" }}>
{lastOne ? project + " | " : project}
</a>
);
}
评估结果为 false,仅列出项目名称 no |
您可能没有将道具传递给
ProjectLinks
,其中 lastOne
是一个假值,因此 |
不会显示。
您可以展开完整的对象来传递所有道具:
{projects.map(p => <ProjectLinks {...p} /> )}
const { useState } = React;
const Example = () => {
const projects = [
{lastOne: false, project: "Kuma", link: "", image: "./kuma.png", },
{lastOne: false, project: "Rin Starseed", link: "", image: "./star.png", },
{lastOne: true, project: "Sea Harvest", link: "", image: "./fish.png", },
];
return (
<div>
{projects.map(p => <ProjectLinks {...p} /> )}
</div>
)
}
function ProjectLinks({ link, project, lastOne }) {
return (
<a href={link} target="_blank" style={{ color: "red" }}>
{lastOne ? project + " | " : project}
</a>
);
}
ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
但这并不是真正可扩展的,因为您需要循环项目数组中的项目,您可以使用循环的迭代器(示例中的
map()
)来检查这是否是列表中的最后一项:
{projects.map((p, i) => <ProjectLinks {...p} lastOne={i === projects.length - 1} /> )}
const Example = () => {
const projects = [
{ project: "Kuma", link: "", image: "./kuma.png", },
{ project: "Rin Starseed", link: "", image: "./star.png", },
{ project: "Sea Harvest", link: "", image: "./fish.png", },
];
return (
<div>
{projects.map((p, i) => <ProjectLinks {...p} lastOne={i === projects.length - 1} /> )}
</div>
)
}
function ProjectLinks({ link, project, lastOne }) {
return (
<a href={link} target="_blank" style={{ color: "red" }}>
{lastOne ? project + " | " : project}
</a>
);
}
ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>