首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在javascript的系统范围主题的基础上向变量发送道具?

如何在javascript的系统范围主题的基础上向变量发送道具?
EN

Stack Overflow用户
提问于 2020-03-11 18:14:04
回答 3查看 126关注 0票数 4

如何在系统范围主题的基础上向组件发送道具?

我知道如何使用@media prefers-color-scheme为深色和浅色主题设置媒体查询的样式,但我正在使用react-json-vew库和组件,它需要一个主题道具,当系统范围的暗色模式被切换时,我需要更改它。

它是一个自定义组件,所以我不想自己设计它的样式,这也会增加代码的长度。

代码片段:

代码语言:javascript
运行
复制
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

  } 
}
EN

回答 3

Stack Overflow用户

发布于 2020-03-11 19:28:15

为什么不使用React Context API呢?

代码语言:javascript
运行
复制
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>
        )
    }
}
票数 1
EN

Stack Overflow用户

发布于 2020-03-11 18:35:04

因此,最简单的方法是接收组件的道具,该道具将描述组件是处于暗模式还是亮模式。我将执行以下示例:

代码语言:javascript
运行
复制
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或某种状态管理,但如果它是一个简单的应用程序,上述方法应该可以工作。

票数 0
EN

Stack Overflow用户

发布于 2020-03-11 18:41:00

这应该能起到作用

代码语言:javascript
运行
复制
<ReactJson src={json} theme={this.props.dark ? "darkThemeName" : "lightThemeName"} />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60633617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档