【问题标题】:How to horizontalize react js component?如何水平化 React js 组件?
【发布时间】:2021-05-29 05:28:34
【问题描述】:

我创建了一个应用来映射页面上的所有卡片组件。但是组件是垂直显示的。我需要每行显示 3 个组件。我怎么能这样表现出来?这是我的代码。

 const[item, setItem] = useState([]);

function addItem(newItem){ //This addItem Part is working.
    setItem(prevItems =>{
        return [...prevItems, newItem]
    });
}

return(<div className="container">
        <div className="row">
        <div className="col-lg-4" style={{cursor: "pointer"}}>
            <AddCard />
        </div>

        <div style={{cursor: "pointer"}}>

            {item.map((items, index)=>{
                return(
                    <div className="col-lg-4" >
                        <ItemCard
                            key={index}
                            id={index}
                            title={items.title}
                            description={items.description}
                        />
                    </div>
                )
        })}
        </div>

        </div>)

【问题讨论】:

  • 这听起来像是一个关于 CSS 的问题,而不是关于 React 的问题。我在你的代码中看到了一些类,比如col-lg-4——我假设这来自你正在使用的一些 CSS 框架。我们可能有必要知道是哪个框架——例如,BootstrapSemantic UI
  • 我正在使用 react-boostrap

标签: javascript css reactjs react-hooks react-bootstrap


【解决方案1】:

您可以在容器上使用 display:"flex"

 const[item, setItem] = useState([]);

function addItem(newItem){ //This addItem Part is working.
    setItem(prevItems =>{
        return [...prevItems, newItem]
    });
}

return(<div className="container">
        <div className="row">
        <div className="col-lg-4" style={{cursor: "pointer"}}>
            <AddCard />
        </div>

        <div style={{cursor: "pointer", display:"flex"}}>

            {item.map((items, index)=>{
                return(
                    <div className="col-lg-4" >
                        <ItemCard
                            key={index}
                            id={index}
                            title={items.title}
                            description={items.description}
                        />
                    </div>
                )
        })}
        </div>

        </div>)

【讨论】:

  • 我需要每行显示 3 个组件。但是如果我使用 'flex' 它会将所有组件显示为一条线。
  • 所以你应该试试:display: "grid", grid-template-columns: "1fr 1fr 1fr"
  • react 中的语法不同,尝试将类添加到容器中并使用 css 添加: .some-container-class{ display: grid;网格模板列:1fr 1fr 1fr;顺便说一句,您可以将“1fr”更改为您想要的任何大小,例如“300px”
【解决方案2】:

使用弹性盒,因为 React 允许您创建组件,因此我们可以像使用弹性盒的 HTML 元素一样设置它们的样式。

例子:

.flexbox-container {
    display: flex;
    flex-direction: row;
}
<div class="flexbox-container">
    <div>Element1</div>
    <div>Element2</div>
    <div>Element3</div>
</div>

【讨论】:

    猜你喜欢
    • 2022-12-21
    • 2020-11-29
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多