React样式组件主题提供者动态主题(React styled

编程入门 行业动态 更新时间:2024-10-24 06:29:11
React样式组件主题提供者动态主题(React styled-components theme-provider dynamic theme)

我正试图在我的反应应用程序中实现黑暗和光明的主题。 我知道主题是如何工作的,所以我设置了我的按钮,例如:

const Button = styled.button` /*some styles*/ color: ${props => props.theme.main};

然后我将主题定义为consts:

const dark = { main: 'black', text: 'switch to light mode'}; const light = { main: 'white', text: 'switch to dark mode' };

当我想使用某个主题时,我会这样做:

<ThemeProvider theme={dark}> <Button>{dark.text}</Button> </ThemeProvider>

但我想要实现的是动态地改变主题(可能是点击功能到按钮)。 我有点新的反应所以请不要对我有意义。

I'm trying to achieve dark and light themes in my React app. I know how themes work, so I'm configuring my button like below, for example :

const Button = styled.button` /* some styles */ color: ${props => props.theme.main} `;

Then I'm defining themes as consts:

const dark = { main: 'black', text: 'switch to light mode' }; const light = { main: 'white', text: 'switch to dark mode' };

And when I want to use the theme somewhere I do it like this:

<ThemeProvider theme={dark}> <Button>{dark.text}</Button> </ThemeProvider>

But what I want to achieve is to change the theme dynamically (on a click function on the button probably). I'm kind of new to React so please don't be mean to me.

最满意答案

像这样的东西? 演示

import React, { Component } from 'react'; import { render } from 'react-dom'; import styled, { ThemeProvider } from 'styled-components'; const themes = { 'light': { main: '#EFEFEF', }, 'dark': { main: '#666', } } const DynamicDiv = styled.div` background: ${({ theme }) => theme.main}; ` class App extends Component { constructor() { super(); this.state = { name: 'React', theme: themes['light'] }; } handleDark = () => { this.setState({ theme: themes['dark'] }) } render() { return ( <ThemeProvider theme={this.state.theme}> <div> <DynamicDiv>{this.state.name}</DynamicDiv> <div onClick={this.handleDark}>Change to Dark</div> </div> </ThemeProvider> ); } } render(<App />, document.getElementById('root'));

Something like this? Demo

import React, { Component } from 'react'; import { render } from 'react-dom'; import styled, { ThemeProvider } from 'styled-components'; const themes = { 'light': { main: '#EFEFEF', }, 'dark': { main: '#666', } } const DynamicDiv = styled.div` background: ${({ theme }) => theme.main}; ` class App extends Component { constructor() { super(); this.state = { name: 'React', theme: themes['light'] }; } handleDark = () => { this.setState({ theme: themes['dark'] }) } render() { return ( <ThemeProvider theme={this.state.theme}> <div> <DynamicDiv>{this.state.name}</DynamicDiv> <div onClick={this.handleDark}>Change to Dark</div> </div> </ThemeProvider> ); } } render(<App />, document.getElementById('root'));

更多推荐

本文发布于:2023-08-07 07:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:主题   提供者   样式   组件   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!