javascript - 如何在 React js 中覆盖 css 模块
问题描述
我的网站有 2 个主题。当我第一次导入一个主题时,它被导入了,第二次它没有改变。我需要更改主题覆盖 css。我该如何解决这个问题?
import React from 'react';
import { Settings } from 'react-feather';
import Modal from 'react-responsive-modal';
export default class ContentConfig extends React.Component {
constructor(props) {
super(props);
this.state = {
openModal: false,
checked: true
};
}
openModal = () => {
this.setState({openModal: true});
}
closeModal = () => {
this.setState({openModal: false});
}
changeRadio = (bool) => {
this.props.state(bool);
this.setState({checked: bool});
}
render() {
return(
<div className="contentConfig">
<div onClick={this.openModal} className="editContentIcon">
<Settings />
<p>Settings</p>
</div>
<Modal open={this.state.openModal} onClose={this.closeModal} center>
<form style={{pading: 20}}>
<legend>Choose a color</legend>
<div className="fieldset">
<div className="colorsBox">
<label htmlFor="radio1" className="colors" style={{background: "#5dafe5"}}></label>
<input
id="radio1"
type="radio"
name="colors"
onChange={() => this.changeRadio(true)}
checked={this.state.checked}
/>
</div>
<div className="colorsBox">
<label htmlFor="radio2" className="colors" style={{background: "#d94f5c"}}></label>
<input
id="radio2"
type="radio"
name="colors"
onChange={() => this.changeRadio(false)}
checked={!this.state.checked}
/>
</div>
</div>
</form>
</Modal>
</div>
);
}
}
这是一个更改主题的子组件,当我选择一个主题时,它会调用父组件中的一个函数。
import React, { Component } from 'react';
import './App.css';
import ContentConfig from './ContentConfig.js';
export default class App extends Component {
constructor() {
super();
}
changeStyles = (bool) => {
if(bool) {
import('./LigthTheme.css').then(() => console.log('imported ligth theme'));
} else {
import('./DarkTheme.css').then(() => console.log('imported dark theme'));
}
}
render() {
return (
<div className="mainBox">
<div className="menu">
<h1>Devices</h1>
<ul className="links">
</ul>
<ContentConfig state={this.changeStyles} />
</div>
</div>
);
}
}
当我第一次在浏览器中更改主题时,它会显示添加到标题中的内容。第二次更改主题后,标题中没有任何变化。
解决方案
我在这里看到 2 个问题,因此您对 CSS 的更改不起作用。
第一的
导入特定主题后,新导入不应有任何影响。由于现在导入了两个 css 文件。
我认为 react 不会卸载之前导入的 css 文件。例如,如果您先导入 LightTheme,然后再导入 DarkTheme,此时这两个都导入到缓存中。
尝试为样式表创建标签,然后动态更改值。那应该可以解决问题。
第二
您没有在调用中传递任何参数 state={this.changeStyles}
。
尝试传递类似state = {this.changeStyles(this, false)}
应该导致 DarkTheme 的东西。
让我知道结果。
这个答案也可能有所帮助。
推荐阅读
- asynchronous - 如何从未来使用列表并在 listView 中使用它
- keras - 是否可以连接来自同一个 ConvNet 的 n 个输出序列并将它们输出到第二个网络而无需存储它们?
- actions-on-google - TypeError: smarthome 不是一个函数
- spring-boot - 我有一个不是主键 ID 的字段。如何通过该非主键使用 JPA 存储库获取数据?
- jquery - location.href 和 location.replace 在 IE 中不起作用
- laravel - Lumen 和 Laravel 上的 Redis 哪个更好?
- html - 闪亮的 HTML 整页 Bootstrap 轮播
- javascript - 如何在我的网络应用程序上推送通知
- azure - 如何通过托管服务器 Microsoft azure 连接我的域(例如:www.xyz.com)?
- python - 如何使用 Python 在 HDFS 中查看传入文件的目录?(Python Script 由 Docker Container 执行;HDFS 中没有 Cronjob)