/*
* @Author: funlee
* @Email: i@funlee.cn
* @Date: 2019-06-06 14:52:06
* @Description: 16.3 旧版实现 依赖注入
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Theme {
constructor(color) {
this.color = color;
this.subscriptions = [];
}
setColor(color) {
this.color = color;
this.subscriptions.forEach(f => f());
}
subscribe(f) {
this.subscriptions.push(f);
}
}
class Button extends Component {
static contextTypes = {
theme: PropTypes.object
}
componentDidMount() {
this.context.theme.subscribe(() => this.forceUpdate());
}
render() {
return(
<button style={{background: this.context.theme.color}}>
{this.props.children}
</button>
)
}
}
class Message extends Component {
render() {
const { id, value } = this.props.data
return(
<li>
{`The ${id} is ${value}`} ---- <Button>Delete</Button>
</li>
)
}
}
class MessageList extends Component {
static childContextTypes = {
theme: PropTypes.object
}
constructor(props) {
super(props);
this.theme = new Theme('red');
}
getChildContext() {
return{
theme: this.theme
}
}
changeColor() {
const colors = ['red', 'pink', 'blue'];
const index = (colors.indexOf(this.theme.color) + 1) % 3;
this.theme.setColor(colors[index]);
}
render() {
const children = this.props.messages.map(message =>
<Message data={message} key={message.id} />
)
return (
<div>
<ul>
{children}
</ul>
<button onClick={() => this.changeColor()}>Change Color</button>
</div>
)
}
}
export default class TestContext extends Component {
render() {
const messages = [
{id: 'name', value: 'funlee'},
{id: 'age', value: 18},
{id: 'skill', value: 'React'}
]
return <MessageList messages={messages} />
}
};
console