/*
* @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';
const Button = (props, context) => {
return(
<button style={{background: context.color}}>
{props.children}
</button>
)
}
Button.contextTypes = {
color: PropTypes.string
}
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 = {
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