react:context跨层级传递参数

大家好,我是梅巴哥er, 本篇介绍context跨层级传递参数。

什么是跨层级传递参数?

  • 正常的参数传递是: 父组件想用孙子组件,需要把参数传递过去。这时候就需要先把参数传给子组件,然后由子组件传递给孙子组件,这样层层传递的过程。
  • 跨层级传递参数是:父组件想用孙子组件,就让组件进行层层传递,但是参数不用再层层传递。把参数放入context里,孙子组件接收这个参数就可以了。

要想用context,先了解一下上篇内容: prop-types, 因为需要用到这个知识。

进入正题---------------

先来看下不跨层级传递参数:

import React, {
    
     Component } from 'react'


class Grandson extends Component {
    
    
    render() {
    
    
        return (
            <header>
            	// 孙子组件接收来自子组件的参数
                {
    
     this.props.title }
            </header>
        )
    }
}

class Child extends Component {
    
    
    render() {
    
    
        return (
        	{
    
    /* 子组件先拿到父组件的参数 
        	然后 传递给孙子组件 */}
            <Grandson title={
    
     this.props.title } />
        )
    }
}
class App5 extends Component {
    
    
    render() {
    
    
        return (
        	{
    
    /* 父组件的参数 title 
        	通过Child组件 传递给子组件*/}
            <Child title='标题' />
        )
    }
}

export default App5

再来看看context跨层级传递参数:

import React, {
    
     Component } from 'react'
import PropTypes from 'prop-types'


class Grandson extends Component {
    
    
	// 3, 设置参数类型 
    static contextTypes = {
    
    
        title: PropTypes.string
    }
    render() {
    
    
        return (
            <header>
            	{
    
    /* 这里说明,携带参数的,已经不是props了,
            	而是context */}
                {
    
     this.context.title }
            </header>
        )
    }
}

class Child extends Component {
    
    
    render() {
    
    
        return (
            <Grandson />
        )
    }
}
class App5 extends Component {
    
    
	// 2,设置参数类型 写法固定
    static childContextTypes = {
    
    
        title: PropTypes.string
    }
    // 1,返回一个对象,里面是携带的参数。固定写法
    getChildContext() {
    
    
        return {
    
    
            title: '标题'
        }
    }
    render() {
    
    
        return (
            <Child />
        )
    }
}

export default App5

context应用场景:
如果需要让参数层层传递,这时候可以用context。但是context并不是唯一的和最好的处理方式。
官方给出的例子中,组合组件也是处理参数传递的不错的选择。

猜你喜欢

转载自blog.csdn.net/tuzi007a/article/details/108038759