美文网首页
React Context 使用笔记

React Context 使用笔记

作者: 拖着蜗牛看风景 | 来源:发表于2019-03-18 23:11 被阅读0次

1、在app.js中 需要通过一个静态属性childContextTypes声明提供给子组件的Context对象的属性。

class App extends Component {

    //先利用childContextTypes声明Context对象属性
    static childContextTypes = {
        title: PropTypes.string
    }
}

2、定义要传送的数据

class App extends Component {

    //先利用childContextTypes声明Context对象属性
    static childContextTypes = {
        title: PropTypes.string
    }

    constructor(props) {
        super(props)
        //然后定义要传递的数据
        this.state = {
            title: '这是标题11'
        }
    }
}

3、利用getChildContext 返回要获取的数据

class App extends Component {
    //先利用childContextTypes声明Context对象属性
    static childContextTypes = {
        title: PropTypes.string
    }

    constructor(props) {
        super(props)
        //然后定义要传递的数据
        this.state = {
            title: '这是标题11'
        }
    }
    //最后返回要获取的数据
    getChildContext() {
        return {
            title: this.state.title
        }
    }
}

在需要的组件中如何使用?
子组件使用方法:


import PropTypes from 'prop-types';

class Post extends Component {
  //利用静态属性contextTypes 获取到要用属性
    static contextTypes = {
        title: PropTypes.string
    }
  //利用this.content.title来获取context传递的值, this.content => object
    render() {
        let datas = this.state.list
        return (
            <div>
                {
                    console.log(this.context.title)
                }
            </div>
        )
    }
}

相关文章

  • React Context 使用笔记

    1、在app.js中 需要通过一个静态属性childContextTypes声明提供给子组件的Context对象的...

  • React Context的使用 React Context能不

    官方给的解释如下 在一个典型的 React 应用中,数据是通过 props 属性自上而下(由父及子)进行传递的,但...

  • React Context 解析

    react Context 是典型的生产者 <=> 消费者模式 1 使用 React.createContext(...

  • 2018-08-08

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

  • react context 的使用

    看了react context 语法,记录一下使用方式 context 的定义 提供了一种方式,能够让数据在组件树...

  • react context的使用

    context:主要为了跨层级通信。 使用步骤 通过 React.createContext()创建一个conte...

  • react context

    React Context 绝大多数应用程序不需要使用 context.如果你想让你的应用更稳定,别使用conte...

  • redux和react-redux的吐槽

    redux使用react还在测试阶段的context脱离传统事件流,只为了能跨组建获取数据,看react-redu...

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

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

  • RN-切换主题-简洁版

    实现功能:切换背景色 使用技术点:context[http://react.caibaojian.com.cn/d...

网友评论

      本文标题:React Context 使用笔记

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