const { useState } = React;
const App = () => {
const [items, setItems] = useState([]);
const [numItems, setNumItems] = useState(0);
return (
<div className="w-full">
<div className="flex p-5 align-center w-full flex-col">
<div className="flex justify-center">
<button
className="border-red-500 border-2 m-2 p-2"
onClick={() => {
addItems("Item " + (numItems + 1));
setNumItems(numItems + 1);
}}
>
Add Item
</button>
</div>
<div className="flex flex-nowrap justify-center align-center p-2 overflow-x-auto border-2 border-blue-700">
{items.map((item) => (
<div className="m-2 p-2 border-red-800 border-2 flex-shrink-0" key={item}>
<h1>{item}</h1>
</div>
))}
</div>
</div>
</div>
);
function addItems(item) {
setItems([...items, item]);
}
};
ReactDOM.render(<App />, document.getElementById("app"));
我正在使用带有React.js 的Tailwind css
在上面的组件中,我有一个按钮,它只需将div水平添加到自动滚动的flexbox中。问题是,我无法从中心添加div,即如果我添加了对齐中心或对齐内容:中心;在normall css中,开头的项目会被剪掉。如何在不丢失项目并保持滚动能力的情况下无限期地添加项目?
代码笔链接:https://codepen.io/vineet192/pen/jOGZQZE
我对您的代码片段做了一些更改,使其能够工作。
基本上剪辑是因为溢出+中心。
const { useState } = React;
const App = () => {
const [items, setItems] = useState([]);
const [numItems, setNumItems] = useState(0);
return (
<div className="w-full">
<div className="flex p-5 align-center w-full flex-col">
<div className="flex justify-center">
<button
className="border-red-500 border-2 m-2 p-2"
onClick={() => {
addItems("Item " + (numItems + 1));
setNumItems(numItems + 1);
}}
>
Add Item
</button>
</div>
<div className="flex flex-nowrap justify-center align-center p-2 overflow-x-hidden border-2 border-blue-700">
<div className='flex overflow-x-auto'>
{items.map((item) => (
<div
className="m-2 p-2 border-red-800 border-2 flex-shrink-0"
key={item}
>
<h1>{item}</h1>
</div>
))}
</div>
</div>
</div>
</div>
);
function addItems(item) {
setItems([...items, item]);
}
};
ReactDOM.render(<App />, document.getElementById("app"));