首页 > 解决方案 > 如何在 React 中仅将 css 应用于此组件?

问题描述

我在我的应用程序中使用 Bootstrap 的 React 模态有一个小问题。

在 index.hmtl 中,我导入了这个:

<link rel="stylesheet" href="/assets/css/bootstrap.min.css">
<link rel="stylesheet" href="/assets/css/bootstrap-theme.min.css">

但是,它将 CSS 应用于我的应用程序中的所有内容。我不想要这个,因为它破坏了整个风格。我无法在我的组件中真正自定义 Bootstrap 中的所有类,因此我需要找到一种方法来仅将这些样式应用于我的模态组件。

这是我的模态:

import React from 'react';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';

import { useTranslation } from 'react-i18next';
import Form from 'components/forms/Form';
import FileInput from 'components/forms/FileInput';

function PicturesUploadModal (props) {
  const { t } = useTranslation('common');

  return (
    <Modal show={props.modalOpen} onHide={props.handleClose}>
      <Modal.Header closeButton>
        <Modal.Title>{ t('addPictures') }</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <p>{ t('numberPics') } {30 - props.images.length}</p>
        <input type="file" onChange={props.handleChange} multiple />
        {(props.error === true) && <p className="alert alert-danger">{t('filesErrors')}</p>}
      </Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={props.handleClose}>
          { t('close') }
        </Button>
        <Button variant="primary" onClick={props.handleSubmit}>
          { t('sendSave')}
        </Button>
      </Modal.Footer>
    </Modal>

  );
}

export default PicturesUploadModal;

那么,如何确保较早导入的样式仅应用于 Modal 组件?

谢谢!

标签: javascriptcssreactjstwitter-bootstrap

解决方案


I suggest you use this awesome library since it's just the modal you are implementing: react-modal will solve your issue, that way bootstrap doesn't mess your styles. Here is the link for the npm package: https://www.npmjs.com/package/react-modal


推荐阅读