如何将来自外部 URL 的样式表应用到特定的 React 组件

How do I apply a stylesheet from external URL to a specific react component

我有几个网页,我有这个:

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>React App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/superhero/bootstrap.min.css">
</head>
<body>
<div class="full-height">
    <div id="app" class="full-height">Loading...</div>
</div>
</body>
<script
        src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
        crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>

如果我用这个

<link rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"  href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/superhero/bootstrap.min.css">

在 index.html 中,我的整个应用程序中的样式都受到影响,但我想在单个组件中使用它们。

我试图通过删除这两行并创建来解决这个问题 chat.scss

#chat{
  @import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css");
  @import url("https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/superhero/bootstrap.min.css");
}

//other import statements
import "../../styles/chat.scss"

然后我将聊天组件的 id 设置为 'chat' 并应用了 scss

export default class Chat extends React.Component {
render() {
    return (
        <div id="chat">
            <div className="full-height">
                <div className="row">
                    <Nav/>
                </div>
                <div className="row full-height">
                    <div className="col-md-3 full-height">
                        <UserProfile/>
                        <OnlineUsers/>
                    </div>
                    <div className="col-md-9 full-height">
                        <div className="full-height">
                            <Messages/>
                            <MessageInput/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

}

此方法与在 index.html 中导入样式表具有相同的输出。它会影响所有页面。

我的问题是如何才能只为我的聊天组件应用这些样式表。

我的解决方案是一种我并不引以为豪的解决方法,但这是您可以在 javascript:

中动态禁用样式表的方法

网页上的所有样式表都可以在 document.styleSheets 集合中找到。 为了抓住第一个给我带来麻烦的:

var stylesheet = document.styleSheets[0];

然后我只是在我的组件中禁用它:

stylesheet.disabled = true;