如何根据系统范围主题向组件发送 Prop ?
我知道如何使用媒体查询为我的组件设置样式,以使用@media Preferred颜色方案,但我正在使用react-json-vew库和组件,它需要一个主题 Prop ,这是我需要的当系统范围的暗模式切换时进行更改。
它是一个自定义组件,所以我不想自己设计它的样式,这也会增加代码的长度。
片段:
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
}
}
最佳答案
为什么不使用 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>
)
}
}
关于javascript - 如何根据 JavaScript 中的系统范围主题将 props 发送到变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60633617/