context
直接上代码
声明context文件
theme-context.js
import React from 'react'
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
export const ThemeContext = React.createContext(
themes.dark // 默认值
);
存储context:
父组件
import react from 'react'
import {ThemeContext, themes} from './theme-context';
import Button from './button'
class model1 extends react.Component{
constructor(props){
super(props)
this.state = {
theme:themes.dark
}
}
render(){
return (
<div>
<ThemeContext.Provider value={this.state.theme}>
<Button></Button>
</ThemeContext.Provider>
</div>
)
}
}
export default model1
取context 时要指定组件的contexttype为哪一个context:
子组件
import {ThemeContext} from './theme-context';
import React from 'react'
class Button extends React.Component {
render() {
let props = this.props;
let theme = this.context;
return (
<button
{...props}
style={{backgroundColor: theme.background}}
/>
);
}
}
Button.contextType = ThemeContext;
export default Button;