/*
* @Author: funlee
* @Email: i@funlee.cn
* @Date: 2019-06-06 14:52:06
* @Description: 16.3 旧版实现 Legacy Context
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
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} />
}
};
class MessageList extends Component {
static childContextTypes = {
color: PropTypes.string
}
constructor(props) {
super(props);
this.state = {
color: 'red'
}
}
getChildContext() {
return{
color: this.state.color
}
}
changeColor() {
const colors = ['red', 'pink', 'blue'];
const index = (colors.indexOf(this.state.color) + 1) % 3;
this.setState({
color: 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>
)
}
}
class Message extends Component {
render() {
const { id, value } = this.props.data
return(
<li>
{`The ${id} is ${value}`} ---- <Button>Delete</Button>
</li>
)
}
}
class Button extends Component {
static contextTypes = {
color: PropTypes.string
}
render() {
return(
<button style={{background: this.context.color}}>
{this.props.children}
</button>
)
}
}
console