美文网首页程序员
react中的context

react中的context

作者: yonglei_shang | 来源:发表于2018-10-12 10:02 被阅读4次

在React中,数据可以以流的形式自上而下的传递,每当你使用一个组件的时候,你可以看到组件的props属性会自上而下的传递。但是,在某些情况下,我们不想通过父组件的props属性一级一级的往下传递,我们希望在某一级子组件中,直接得到上N级父组件中props中的值这时就用到了context

使用

  • 首先安装依赖 prop-types(在React v15.5 开始 ,React.PropTypes 助手函数已被弃用,我们建议使用 prop-types 库 来定义contextTypes)
npm install prop-types --save
  • 定义组件
    button.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Button extends Component {
  render () {
    return (
      <div>
        <button>{this.context.color}</button>
      </div>
    )
  }
}

Button.contextTypes = {
  color: PropTypes.string
}

export default Button

message.js

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Button from './button.js'

class Message extends Component {
  render () {
    return (
      <div>
        <Button></Button>
      </div>
    )
  }
}

export default Message 

messageList

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Message from './message.js'

class MessageList extends Component {
// 首先要定义 childContextTypes 
  static childContextTypes = {
    color: PropTypes.string
  }
// 通过getChildText方法,来给子context对象的属性赋值
  getChildContext () {
    return {
      color: '蓝色'
    }
  }
  render () {
    return (
      <div>
        <Message ></Message >
      </div>
    )
  }
}
// 此处的和上面 static定义取一个就行
// MessageList.childContextTypes = {
//   color: PropTypes.string
// }

export default MessageList 

相关文章

  • React中不常用的功能——Context

    React中不常用的功能——Context Context React源码版本16.8 基本用法 跨层级通信 Co...

  • React-深入探究Context(1)

    前言 React组件中的Context与Android中的Context类似,都可以理解为上下文。而React中的...

  • 2018-08-08

    React 高级指南 React 新版上下文(context) context ?答:上下文(Context) 提...

  • react中的context

    在React中,数据可以以流的形式自上而下的传递,每当你使用一个组件的时候,你可以看到组件的props属性会自上而...

  • react 中的context

    context 表示上下文,将好像组件里面的全局变量一样,一般我们不使用这个属性,因为这个有可能损坏组件。指定 c...

  • React 中的Context

    当我们想在组件树内传递props,并且不想让props流经树的每一层,context会让我们做到这一点。conte...

  • React中 的 Context

  • 关于react中的context

    一、context有什么用 当我们使用props进行组件中的数据传递时,假如祖先级组件的数据要传递至孙子级,这种情...

  • React中的Context理解

    今天看了下react官网的context,记录下学习过程和自己对context的理解。下面从为什么要用和怎么用两个...

  • React 中的 context(7)

    Context 作用:给整个组件树共享全局的数据 最适合的场景:杂乱无章的组件都需要同一些数据 如果单纯为了不层层...

网友评论

    本文标题:react中的context

    本文链接:https://www.haomeiwen.com/subject/uawbaftx.html