如何将样式表从外部URL应用到特定的react组件



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

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中,我的整个应用程序中的样式都会受到影响,但我想在单个组件中使用它们。

我试图通过删除这两行并创建聊天.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设置为"聊天",并应用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;

最新更新