我有这个 jsx 表达式,它使用 map 函数从数组中渲染最多 5 个项目。如何才能使其余项目在单击按钮时呈现?数组中的项目列表未知,因为它来自 API,因此有时可能是 10 个项目或 15 个项目等。
const Second = ({container}) => {
return(
<div>
{container?.slice(0, 5).map((container) => (
<h3>{container}</h3>
))}
<button type="button" class="btn btn-primary">Primary</button>
</div>
)
}
最佳答案
您可以有一个状态来确定这一点,然后在单击按钮时将状态设置为true
:像这样的
const Second = ({container}) => {
const [showMore, setShowMore] = useState(false);
return(
<div>
{container?.slice(0, 5).map((container) => (
<h3>{container}</h3>
))}
{showMore && container?.slice(5).map((container) => (
<h3>{container}</h3>
))} //this would show the remaining values
<button type="button" class="btn btn-primary" onClick={() => setShowMore(true)}>Primary</button>
</div>
)
}
关于javascript - 如何通过单击按钮从 map 功能加载更多项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69245567/