react中context的使用(es6)

context的作用

context 通过组件数提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。

在一个典型的 React 应用中,数据是通过 props 属性由上向下(由父及子)的进行传递的,但这对于某些类型的属性而言是极其繁琐的(例如:地区偏好,UI主题),这是应用程序中许多组件都所需要的。 Context 提供了一种在组件之间共享此类值的方式,而不必通过组件树的每个层级显式地传递 props 。

在react中实现context的使用

//使用context中值的组件
import React from 'react';
import PropTypes from 'prop-types';
class Button extends React.Component {
  render() {
    return (
      // context中的值具体的使用
      <button style={{background: this.context.color}}>
        {this.props.children}
      </button>
    );
  }
}

Button.contextTypes = {
  color: PropTypes.string
};

// 中间的组件
import React from 'react';
class Message extends React.Component {
  render() {
    return (
      <div>
        {this.props.text} <Button>Delete</Button>
      </div>
    );
  }
}

// 顶级组件,在配置context的值
import React from 'react';
import PropTypes from 'prop-types';
class MessageList extends React.Component {
  getChildContext() {
  // 设置context中color的具体值
    return {color: "purple"};
  }

  render() {
    const children = this.props.messages.map((message) =>
      <Message text={message.text} />
    );
    return <div>{children}</div>;
  }
}

MessageList.childContextTypes = {
  // 指定context中存在color,对应的值为字符串类型
  color: PropTypes.string
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 Context被翻译为上下文,在编程领域,这是一个经常会接触到的概念,React中也有。 在React的官方...
    张国钰阅读 54,619评论 17 113
  • 深入JSX date:20170412笔记原文其实JSX是React.createElement(componen...
    gaoer1938阅读 8,116评论 2 35
  • 以下内容是我在学习和研究React时,对React的特性、重点和注意事项的提取、精练和总结,可以做为React特性...
    科研者阅读 8,309评论 2 21
  • 3. JSX JSX是对JavaScript语言的一个扩展语法, 用于生产React“元素”,建议在描述UI的时候...
    pixels阅读 2,925评论 0 24
  • 语言真是个好东西 每次阅读每次感动 我喜欢看你们唠嗑 或许抱怨生活艰辛 或许狂晒每日喜乐 因为生活是个过程 没有经...
    毛girl阅读 356评论 0 1