首页 > 解决方案 > 将 React-Bootstrap xs,sm,md,lg,xl 跨度/偏移量保存到 css 类中

问题描述

我们有以下<Row>两个<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 }}在我们的应用程序中添加诸如此类的东西会使代码更加混乱。

谢谢!

标签: cssreactjsreact-bootstrapbootstrap-grid

解决方案


你为什么不简单地为此创建一个组件?类似的东西(演示)

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"));

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

例如,如果你想在 col 上添加或更改类,你可以添加一个 prop。


推荐阅读