React context跨级父传子

import  React, {Component}  from 'react';
import { PropTypes } from 'prop-types';

class ListItem extends Component {
  static contextTypes = {
    color: PropTypes.string
  }
  render(){
    const  { value } = this.props;
    return (
      <li style={{background:this.context.color}}>
        <span>{value}</span>
      </li>
    )
  }
}

class List extends Component {
  static childContextTypes = {
    color : PropTypes.string
  }

  getChildContext(){ //过时api
    return {
      color:'red'
    }
  }
  render(){
    const {list} = this.props;
    return (
      <div>
        {
          list.map((entry,index)=>
            <ListItem key={`list-${index}`}  value={entry.text}  />
          )
        }
      </div>
    )
  }
}

export default class Home extends Component {

  render(){
    const list = [
      {text:'orange'},
      {text:'apple'}
    ];
    return (
      <div>
        列表
       <List list={list} />
      </div>
    )
  }
}

posted @ 2020-03-31 15:14  橙云生  阅读(190)  评论(0编辑  收藏  举报