React Context
将公共的变量抽离到顶部,注入到组件当中。涉 及到的核心 API 有三个。
创建 Context
使用 React.createContext 创建 Context 组件
export interface Theme {
foreground: string;
background: string;
}
export interface Themes {
light: Theme;
dark: Theme;
[key: string]: Theme;
}
export const themes: Themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
const ThemeContext = createContext<ThemeContextInterface>({
theme: themes.dark,
setTheme: () => {},
});
注入 Context
通过 ThemeContext.Provider 注入 Context,必添参数 value 指定 Context 的值。
<ThemeContext.Provider value={ { theme, setTheme } }>
{ props.children }
</ThemeContext.Provider>