另一种基于Array.prototype.slice()方法的方法
在父组件中的使用
import React from "react";
import { ColorList } from "./Color";
export default function App() {
return <ColorList colors={["red", "green", "blue"]} visibleItemsCount={1} />;
}
该ColorList
组件如下所示:
import React from "react";
// This is just a placeholder component :)
function Color({ color }) {
return <div style={{ color }}>{color}</div>;
}
export function ColorList({ colors, visibleItemsCount = 0 }) {
const [showMore, setShowMore] = React.useState(false);
// Toggle value on click button
const onClick = () => setShowMore((value) => !value);
// Memoize the color list when props changed
const visibleColors = React.useMemo(() => {
// If show more items, return the whole array
// Otherwise, return a sliced array based on visible items
const count = showMore ? colors.count : visibleItemsCount;
return colors.slice(0, count);
}, [colors, visibleItemsCount, showMore]);
console.log(visibleColors);
return (
<>
<h1>Color list</h1>
<>
{visibleColors.map((color) => (
<Color key={color} color={color} />
))}
</>
<button onClick={onClick}>{showMore ? "Show less" : "Show more"}</button>
</>
);
}
注意:我在 CodeSandbox 上上传了代码,你可以在这里查看