如何在系统范围主题的基础上向组件发送道具?
我知道如何使用@media prefers-color-scheme为深色和浅色主题设置媒体查询的样式,但我正在使用react-json-vew库和组件,它需要一个主题道具,当系统范围的暗色模式被切换时,我需要更改它。
它是一个自定义组件,所以我不想自己设计它的样式,这也会增加代码的长度。
代码片段:
import ReactJson from "react-json-view";
import React from "react";
class JsonDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false,
copied: false
};
}
render(){
return <ReactJson src={json} theme={"apathy:inverted"} /> // here I need to apply theme on the basis of dark or light mode
}
}
发布于 2020-03-11 19:28:15
为什么不使用React Context API呢?
import React from 'react';
const ThemeContext = React.createContext();
export default class App extends React.Component {
render() {
return (
<ThemeContext.Provider value={'apathy:inverted'}>
<JsonDialog/>
{/* Other Components */}
</ThemeContext.Provider>
)
}
}
class JsonDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false,
copied: false
};
}
render() {
return(
<ThemeContext.Consumer>
{theme=> <ReactJson src={json} theme={theme} />}
</ThemeContext.Consumer>
)
}
}
发布于 2020-03-11 18:35:04
因此,最简单的方法是接收组件的道具,该道具将描述组件是处于暗模式还是亮模式。我将执行以下示例:
import ReactJson from "react-json-view";
import React from "react";
class JsonDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false,
copied: false
};
}
render(){
const themeName = this.props.dark ? 'apathy':'apahty:inverted'
return <ReactJson src={json} theme={themeName} /> // here I need to apply theme on the basis of dark or light mode
}
}
另一种方法是对你的应用程序使用redux或某种状态管理,但如果它是一个简单的应用程序,上述方法应该可以工作。
发布于 2020-03-11 18:41:00
这应该能起到作用
<ReactJson src={json} theme={this.props.dark ? "darkThemeName" : "lightThemeName"} />
https://stackoverflow.com/questions/60633617
复制相似问题