使用Typescript的React的Context API

问题描述

我有一个demo

它是一个使用Typescript的简单React应用。

我正在尝试使用Reacts Context API

我创建了一个上下文ThemeContext,该上下文具有简单的主题样式值,可用于其他组件。

然后,我尝试使用此主题上下文来设置书籍列表的样式-Booklist.tsx

我的问题是我根本无法正常工作,什么也没显示

对不起,我知道这很模糊,但是任何人都可以帮忙看看我要怎么做。

index.tsx

import React from 'react';
import BookList from './Booklist';
import ThemeContextProvider from './ThemeContext';

const App:React.FC = () => {
  return (
    <div className="App">
      <ThemeContextProvider>
        <BookList />
      </ThemeContextProvider>
    </div>
  );
}

export default App;

ThemeContext.tsx

import React,{createContext} from 'react'

export interface Props {}

export interface State {
    lightTheme: boolean
    light:{Syntax: string,ui: string,bg: string}
    dark:{Syntax: string,bg: string}
    toggleTheme:boolean
}

const defaultState:State = {
    lightTheme: true,light:{Syntax:'',ui:'',bg:''},dark:{Syntax:'',toggleTheme:false
}

export const ThemeContext = createContext(defaultState)

class ThemeContextProvider extends React.Component<Props,State> {

    constructor(props: Props){
        super(props)

        this.state = { 
            lightTheme: true,light: {Syntax: '#555',ui: '#ddd',bg: '#eee'},dark: {Syntax: '#ddd',ui: '#333',bg: '#555'},toggleTheme: false
        }
    }

    render() { 
        return (  
            <ThemeContext.Provider value={{...this.state}}>
                {this.props.children}
            </ThemeContext.Provider>
        );
    }
}

export default ThemeContextProvider;

Booklist.tsx

import React from 'react'
import { ThemeContext } from './ThemeContext';

export interface Props {}

export interface State {
    lightTheme: boolean
    light:Darkness
    dark:Darkness
}

interface Darkness{
    Syntax: string
    ui: string
    bg: string 
}

class BookList extends React.Component<Props,State> {
    render() { 
      return(
        <ThemeContext.Consumer>
        {(state) => {
          const { lightTheme,light,dark} = this.state
          const theme = lightTheme ? light : dark
          return(
                  <div style={{color: theme.Syntax,background: theme.bg}}>
                      <ul>
                          <li style={{background:theme.ui}}>Book One</li>
                          <li style={{background:theme.ui}}>Book Two</li>
                      </ul>
                  </div>
          )
        }}</ThemeContext.Consumer>
      )
    }
}

export default BookList;

解决方法

你失踪了 渲染

import { render } from "react-dom";
render(<App />,document.getElementById("root"));

in your demo