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'));更多推荐
发布评论