美文网首页
react 之Context理解

react 之Context理解

作者: feeling_1f11 | 来源:发表于2017-11-22 10:40 被阅读468次

通常情况下,在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将会是个空对象。





相关文章

  • react 之Context理解

    通常情况下,在react组件中,我们可以通过props很清楚的知道哪些数据被传递,但是在一些特定的场景下,我们不想...

  • React-深入探究Context(1)

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

  • React 拾遗之 Context

    React 拾遗之 Context React.js 的 context 其实像就是组件树上某颗子树的全局变量 使...

  • 2018-08-08

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

  • React中的Context理解

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

  • React 之 Context API(二)

    一、前言 在《React 之 Context API(一)[https://www.jianshu.com/p/4...

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

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

  • 012|React之Context

    假设有层级 A->B->C->D,如果A需要传递一个参数给D,根据前文的知识,只能通过props参数一层一层传递。...

  • 疑问汇总

    1. react context是怎样实现 跨组件通信的? 从Context源码实现谈React性能优化[http...

  • React扩展之Fragment&Context&PureCom

    Fragment Context PureComponent 点赞加关注,永远不迷路 上一篇:React扩展之懒加...

网友评论

      本文标题:react 之Context理解

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