在App.css中,我有
.theme {
color: green;
}
我有 className="theme" 分散在多个组件中。
有没有办法将事件的主题颜色从绿色更改为蓝色?
如果没有,我应该如何设计我的代码?
好吧,您可以创建 2 个名为.blue-theme
和.green-theme
的类
每当发生某些事件时,
onClick = (themeCol) => {
this.setState({theme:thmeCol})
}
render(){
return(
<button onClick={()=>onClick('blue-theme')}>Blue theme</button>
<button onClick={()=>onClick('green-theme')}>Green theme</button>
<div className={this.state.theme}> Sample </div>
)
}
您可以传递主题的值。
你可以试试
const themeClass = "";
if (event-as-wanted){
themeClass="theme";
}
className={themeClass}
您也可以在同一文件中使用样式而不是类名
const theme ={
color: '';
};
style={theme}
并用诸如
if (event-as-wanted){
theme.color = "green";
}
您可以有条件地呈现<style/>
标签以覆盖整个文档中类的样式定义。
class App extends React.Component {
state = {
red: true,
}
render() {
return (
<div>
<div className="foo">Foo</div>
<button onClick={() => this.setState({ red: !this.state.red })}>
Toggle Red
</button>
{this.state.red && <style>{".foo { color: red }"}</style>}
</div>
);
}
}
请记住,在 JSX 标记中,大括号将被解释器拾取,并可能破坏解析器。为了避免这种情况,你应该把你的CSS放在一个字符串中,如上例所示。
向 CSS 文档添加<style/>
标记将覆盖在此之前的任何同样具体的 CSS 规则。一旦不再满足条件,将删除样式标记并恢复原始样式。
在 React 中.js只需将颜色状态设置为任何颜色,然后在单击事件中切换颜色
class App extends React.Component {
constructor(props) {
super(props);
this.state = {color: green};
this.changeColor = this.changeColor.bind(this);
}
changeColor() {
const newcolor = this.state.color == green ? blue : green;
this.setState({ color: newcolor});
}
render() {
return (
<div class="theme" style={{color: this.statecolor}}>
<button onClick={this.changeColor}>
</button>
//put all html withing the parent DOM of element with class theme accordingly or it wont render.
</div>
);
}
创建两个类,.green-theme{
color:'green'}
和类似的蓝色主题。 曼坦REDUX STATE
,CURRENT_THEME。事件触发后,相应地更改 redux 状态,并在要使用 CURRENT_THEME 的所有位置使用mapStateToProps
使用它。
我宁愿尝试使用几乎纯粹的CSS解决方案:
在应用程序中.css
#App.first-theme .theme { color:green; }
#App.second-theme .theme { color:blue; }
在应用的渲染中:
<div id="App" className={this.state.currentTheme}>
<AnotherComponent1 />
<AnotherComponent2 />
</div>
您需要做的就是适当地更改this.state.currentTheme
。您甚至可以使用从 redux 注入的 prop。
这里发布的几乎所有其他解决方案都有相同的缺陷:您必须调整所有组件以使用该主题。使用此解决方案,无需在组件中执行其他代码即可更改应用的外观。
相信我,从 redux store/react 上下文中为每个组件注入相同的属性会让你头疼和大量不必要的代码。
您还应该尽量避免生成额外的<style>
标签 - 您最终会在一个文件中拥有大量的!important
和 HTML、逻辑和 CSS。真是一团糟!想象一下,如果你将来想使用 SCSS,会发生什么......