方案一:grid 布局
// tailwind.css plugin
/** @type {import('tailwindcss').Config} */
export default {
content: ["./src/**/*.{jsx,tsx,js,ts}"],
theme: { ... },
plugins: [
function({ matchUtilities }) {
matchUtilities(
{
"counter-reset": (value) => ({ "counter-reset": value }),
"counter-increment": (value) => ({ "counter-increment": value }),
},
)
},
],
};
// ColumnTable component
import { useState } from "react";
const ColumnTable = () => {
const [count, setCount] = useState(10);
const handleMinus = () => {
setCount(count - 1 < 0 ? 0 : count - 1);
};
const handleAdd = () => {
setCount(count + 1);
};
return (
<div className="w-full px-5 text-center text-white-1">
<div
className="w-full h-[300px] border-2 border-orange-500 grid gap-4 grid-flow-col counter-reset-[num]"
style={{
gridTemplateColumns: "repeat(3, 1fr)",
gridTemplateRows: `repeat(${Math.ceil(count/3)}, 1fr)`
}}
>
{Array.from({ length: count })
.map((_, index) => (
<div
className="counter-increment-[num] flex items-center justify-center bg-pri-1"
key={index}
>
{index}
</div>
))
}
</div>
<div className="flex">
<div
className="bg-pri-1 h-[44px] p-4 flex-1 flex items-center justify-center"
onClick={handleMinus}
>
-
</div>
<div
className="bg-pri-1 h-[44px] p-4 flex-1 flex items-center justify-center ml-[1px]"
onClick={handleAdd}
>
+
</div>
</div>
</div>
);
};
export default ColumnTable;
方案二:columns布局
// ColumnsTable component
import { useState } from "react";
const heights = [
100,
160,
400,
30,
83,
45,
200
];
const ColumnsTable = () => {
const [count, setCount] = useState(10);
const handleMinus = () => {
setCount(count - 1 < 0 ? 0 : count - 1);
};
const handleAdd = () => {
setCount(count + 1);
};
return (
<div className="w-full px-5 text-center text-white-1">
<div
className="w-full border-2 border-orange-500 columns-3 gap-3"
>
{Array.from({ length: count }).map((_, index) => (
<div
className="flex items-center justify-center bg-pri-1 mb-2"
style={{ height: heights[Math.floor(Math.random() * count)] }}
key={index}
>
{index}
</div>
))}
</div>
<div className="flex">
<div
className="bg-pri-1 h-[44px] p-4 flex-1 flex items-center justify-center"
onClick={handleMinus}
>
-
</div>
<div
className="bg-pri-1 h-[44px] p-4 flex-1 flex items-center justify-center ml-[1px]"
onClick={handleAdd}
>
+
</div>
</div>
</div>
);
};
export default ColumnsTable;