/*
* @Author: funlee
* @Email: i@funlee.cn
* @Date: 2019-06-06 14:52:06
* @Description: 16.3 旧版实现 Legacy Context
* 如果最靠近的父组件也提供context
* context在遇到同名Key值时肯定取的是最靠近的父组件。
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Button extends Component {
static contextTypes = {
color: PropTypes.string
}
render() {
return(
<button style={{background: this.context.color}}>
{this.props.children}
</button>
)
}
}
class Message extends Component {
static childContextTypes = {
color: PropTypes.number
}
constructor(props) {
super(props);
this.state = {
color: 100
}
}
getChildContext() {
return {
color: this.state.color
}
}
render() {
const { id, value } = this.props.data
return(
<li>
{`The ${id} is ${value}`} ---- <Button>Delete</Button>
</li>
)
}
}
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>
)
}
}
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