【问题标题】:Save React-Bootstrap xs,sm,md,lg,xl spans/offsets into css class将 React-Bootstrap xs、sm、md、lg、xl 跨度/偏移量保存到 css 类中
【发布时间】:2025-12-22 03:40:15
【问题描述】:

我们有以下 <Row> 和 2 个 <Col> 元素:

<Row>
    <Col xs={12} sm={{ span: 9, offset: 1 }} md={{ span: 6, offset: 0 }} lg={5} xl={4}>
        <h3 className='graph-header-1'>First Header</h3>
        <div>Graph that fills the col-width goes here</div>
    </Col>
    <Col xs={12} sm={{ span: 9, offset: 1 }} md={{ span: 6, offset: 0 }} lg={{ span: 5, offset: 1 }} xl={{ span: 4, offset: 2 }}>
        <h3 className='graph-header-1'></h3>
        <div>2nd Graph that fills the column's width goes here</div>
    </Col>
</Row>

这种布局(有 2 个列的行,每个 xs、sm、md、lg、xl 都有这些特定的跨度/偏移量)将在我们应用程序的几个地方使用。是否可以将其保存在一个类中,这样我们就不必一遍又一遍地设置这些值,而只需使用:

<Row className='our-responsive-layout'>
    <Col>
        <h3 className='graph-header-1'>First Header</h3>
        <div>Graph that fills the col-width goes here</div>
    </Col>
    <Col>
        <h3 className='graph-header-1'></h3>
        <div>2nd Graph that fills the column's width goes here</div>
    </Col>
</Row>

...our-responsive-layout 是一个处理 2 列的跨度/偏移量的类?或者,为每列设置一个类(而不是为 2 列的行设置一个类)也会有所帮助。

编辑:如果有任何关于使用 react-bootstrap 及其容器/行/列组件在复杂的 react-app 中处理响应性的详尽指南,请分享。我担心在我们的应用中添加xs={12} sm={{ span: 9, offset: 1 }} md={{ span: 6, offset: 0 }} lg={{ span: 5, offset: 1 }} xl={{ span: 4, offset: 2 }} 之类的东西会使代码更加混乱。

谢谢!

【问题讨论】:

    标签: css reactjs react-bootstrap bootstrap-grid


    【解决方案1】:

    您为什么不简单地为此创建一个组件?某事like that (demo)

    import React, { Component } from "react";
    import { render } from "react-dom";
    
    const App = () => {
      return (
        <MyRow>
          <MyCol>Here is your col 1</MyCol>
          <MyCol>Here is your col 2</MyCol>
        </MyRow>
      );
    };
    
    const MyRow = ({children}) => {
      return <div className='this is your row'>{children}</div>
    }
    
    const MyCol = ({children}) => {
      return <div className='this is your col'>{children}</div>;
    }
    
    render(<App />, document.getElementById("root"));
    
    

    在这里,您只需将 MyRowMyCol 中的 div 标签(当然还有 className)替换为您的 rows 和 col 组件,就足够了。

    例如,如果您想在 col 上添加或更改类,则只需添加一个 prop。

    【讨论】:

    • 这可能是一个愚蠢的问题,但它不是我曾经熟悉的东西 - 在组件内部传递的任何内容:Here is your col 1 在上面的示例中,自动/始终可用于MyCol作为children?
    • @Canovice 是的,这就是组件在 React 中的工作方式。调用组件有两种方式:&lt;MyCol /&gt;(自闭)和&lt;MyCol&gt;blabla&lt;/MyCol&gt;(..不是自闭?哈哈)。在这里,您在非自封闭版本中传递的任何内容都会在children 中检索。它可以是简单的文本,也可以是其他组件(至于MyRow)。
    • 好的,谢谢。每当我需要将任何东西传递给组件时,我总是将它作为道具传递。我不确定children 的好处超过明确命名的道具,但我会研究它。谢谢
    • @Canovic 不客气 :) 它防止使用道具,在你的 jsx 中也更容易阅读,当然,孩子们可以接受你想要的任何东西。实际上,children 是一个 prop,你不需要声明它,因为 React 已经知道它。我大部分时间都将这种组件用于架构行为。