首页 > 其他 > 详细

React context跨级父传子

时间:2020-03-31 15:36:29      阅读:61      评论:0      收藏:0      [点我收藏+]
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>
    )
  }
}

React context跨级父传子

原文:https://www.cnblogs.com/chengyunshen/p/12605391.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!