【问题标题】:Why does styling a Bootstrap modal with dialogClassName set and using Styled JSX require the global tag?为什么设置 dialogClassName 并使用 Styled JSX 设置 Bootstrap 模式的样式需要全局标记?
【发布时间】:2020-01-20 23:13:06
【问题描述】:

我正在使用带有 Bootstrap 和样式 JSX 的 Next.js (React)。我遇到了一个问题,即 Bootstrap 中用于模态的自定义类仅在 css 为全局时才使用 css 样式。我使用 Modal 上的 dialogClassName 属性声明自定义类。这是我的函数组件(我正在使用 Typescript):

const Form: React.FunctionComponent<props> = (props: props) => {
  const [FormVisibility, FormDispatch] = useContext(FormContext);
  return (
      <Modal
        show={props.isVisible}
        onHide={() => {FormDispatch({ type: ActionTypes.CloseForm }) }}
        backdrop="static"
        dialogClassName="custom-modal"
        >
        <Modal.Header closeButton >
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => {FormDispatch({ type: ActionTypes.CloseForm }) }}>
            Close
          </Button>
        </Modal.Footer>
        <style jsx global>{`
      .custom-modal {
        color: blue;
        height: 75vh;
        width: 75vw;
        max-width: none !important;
      }
      `}
      </style>
      </Modal>
  );
}

这很好用。但是如果我将&lt;style jsx global&gt; 更改为&lt;style jsx&gt;,则不会应用样式。我在这里做错了什么还是有更好的方法来做到这一点?对我来说似乎很奇怪,即使组件在本地声明了类,也需要 global。

谢谢!

【问题讨论】:

    标签: css reactjs twitter-bootstrap jsx next.js


    【解决方案1】:

    我使用 Modals 的经验是,modal 元素实际上是从组件所在的 DOM 树中提取出来的,并放置在 body 标签下方的最顶层。

    <body>
       // Component where the Modal is declared
       <Form />
       <div>
        // Modal appears here
        // Styles are not applied because Modal is not nested within Form component
       </div>
    </body>
    

    由于这个原因,您的本地样式可能未应用。

    【讨论】:

    • 啊,你说得对,我什至没有注意到是这样的。谢谢!您认为有更好的方法来设置模态样式吗?
    • 我看不出你现在所做的有什么问题。如果您热衷于继续使用样式化的 JSX,那么可以尝试使用一次性全局选择器 github.com/zeit/styled-jsx#one-off-global-selectors。如果您想在该组件的本地范围内添加其他类,这可以确保只有 custom-modal 类是全局范围的。
    • 一次性全局选择器听起来是个不错的方法。我会看看。感谢您的反馈!
    猜你喜欢
    • 2014-04-06
    • 2014-03-31
    • 1970-01-01
    • 2020-04-04
    • 2020-12-16
    • 2021-07-13
    • 2015-04-17
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多