旧版
import React from 'react';
import ReactDOM from 'react-dom';
const Component = React.PureComponent;
class Index extends Component {
static childContextTypes = {
themeColor: '',
}
constructor () {
super()
this.state = { themeColor: 'red' }
}
getChildContext () {
return { themeColor: this.state.themeColor }
}
render () {
return (
<div>
<Header />
<Main />
</div>
)
}
}
class Header extends Component {
render () {
return (
<div>
<h2>This is header</h2>
<Title />
</div>
)
}
}
class Title extends Component {
static contextTypes = {
themeColor: '',
}
render () {
return (
<h1 style={{color: this.context.themeColor}}>React.js 小书标题</h1>
)
}
}
ReactDOM.render(
<Index />,
document.getElementById('root')
)
新版
import React from 'react';
import ReactDOM from 'react-dom';
const ThemeContext = React.createContext({
background: '',
color: ''
});
class Index extends React.Component {
render () {
return (
<ThemeContext.Provider value={{background: 'green', color: 'red'}}>
<Header />
</ThemeContext.Provider>
);
}
}
class Header extends React.Component {
render () {
return (
<Title>Hello React Context API</Title>
);
}
}
class Title extends React.Component {
render () {
return (
<ThemeContext.Consumer>
{context => (
<h1 style={{background: context.background, color: context.color}}>
{this.props.children}
</h1>
)}
</ThemeContext.Consumer>
);
}
}
ReactDOM.render(
<Index />,
document.getElementById('root')
)
网友评论