react 之Context理解

通常情况下,在react组件中,我们可以通过props很清楚的知道哪些数据被传递,但是在一些特定的场景下,我们不想要手动的向下每一层传递我们需要的props,这就需要用到强大的context API了。

首先是一个不使用context的例子:

这里使用了this.props.children,所有嵌套在组件中的 JSX 结构都可以在组件内部通过 props.children 获取到:

import React from 'react';

export  class Button extends React.Component {
    render() {
        return (
           <button style={{background: this.props.color}}>
                {this.props.children}
           </button>
        );
    }
}



export  class Message extends React.Component {
    render() {
        return (
            <div>
                <Button color={this.props.color}>Delete</Button>
            </div>
        );
    }
}


export class MessageList extends React.Component {
    render() {
        const color = "purple";
        return (
            <Message  color={color} />
        )
    }
}
然后修改为使用context:
import React from 'react';
import PropTypes from 'prop-types';

export  class Button extends React.Component {
    render() {
        return (
            <button style={{ background: this.context.color }}>
                {this.props.children}
            </button>
        );
    }
}
Button.contextTypes = {
    color: PropTypes.string
};


export  class Message extends React.Component {
    render() {
        return (
            <div>
                <Button >Delete</Button>
            </div>
        );
    }
}


export class MessageList extends React.Component {
    getChildContext() {
        return { color: "purple" };
    }
    render() {
        return (
            <Message />
        )
    }
}
MessageList.childContextTypes = {
    color: PropTypes.string
};


通过在MessageList(context提供者)中添加childContextTypes和getChildContext,React会向下自动传递参数,任何组件只要在它的子组件中(这个例子中是Button),就能通过定义contextTypes来获取参数。

如果contextTypes没有定义,那么context将会是个空对象。





©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 深入JSX date:20170412笔记原文其实JSX是React.createElement(componen...
    gaoer1938阅读 12,476评论 2 35
  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 7,858评论 1 18
  • It's a common pattern in React to wrap a component in an ...
    jplyue阅读 8,529评论 0 2
  • 本笔记基于React官方文档,当前React版本号为15.4.0。 1. 安装 1.1 尝试 开始之前可以先去co...
    Awey阅读 12,325评论 14 128
  • react 基本概念解析 react 的组件声明周期 react 高阶组件,context, redux 等高级...
    南航阅读 4,717评论 0 1

友情链接更多精彩内容