Back

【React记录】react class组件context组件传值方式

1.通过createContext传递context

使用步骤
1.从react中引入react-hooks中的createContext,定义一个const TextContext=createContext(null)。
2.使用TextContext.Provider包裹子组件,使用value传递context参数。
3.在下级组件使用静态属性contextType 获取到上层组件中的context,然后就会把传递的参数挂载到当前组件的this.context上。

代码如下

import React, { createContext, Component } from 'react'
// 借助context 可以让我们无须明确地传遍每一个组件,就能将值深入传递进组件树。
const TextContext = createContext(null);

class Parent extends Component {
  render() {
    // 使用一个 Provider 来将当前的 theme 传递给以下的组件树。
    // 无论多深,任何组件都能读取这个值。
    // 在这个例子中,我们将 “dark” 作为当前的值传递下去。
    return (
      <TextContext.Provider value={{ count: 1 }}>
        <Child />
      </TextContext.Provider>
    );
  }
}

// 中间的组件再也不必指明往下传递 theme 了。
function Child(props) {
  return (
    <div>
      <Son />
    </div>
  );
}

class Son extends Component {
  // 使用静态属性contextType 获取到上层组件中的context;             
  static contextType = TextContext;
  render() {
    const { count } = this.context
    return (
        <>
            { count }
        </>
    )
  }
}

2.通过方法getChildContext方法传递

使用步骤:
1.在父组件定义getChildContext方法,return要传递的值。
2.父组件定义静态属性ChildContextTypes,规定传递context的类型。
3.在下级组件需要用到上级context属性的地方,使用静态属性contextTypes接收,然后参数就会传递到当前组件的this.context上。

代码如下

import React, { Component } from 'react'
import PropTypes from 'prop-types'
// 孙组件
class Son extends Component {
    // 孙组件使用静态方法 static contextTypes来接收上级组件传递过来的context属性
    // 如果只在contextTypes属性里面只定义来一个属性color,则打印信息为{color: "purple"}
    static contextTypes = {
        color: PropTypes.string,
        text: PropTypes.string
    }
    componentDidMount() {
        console.log(this.context) // {color: "purple", text: "item text"}
    }
    render() {
        return null
    }
}
// 子组件
class Child extends Component {
    componentDidMount() {
        // 子组件未使用静态属性static contextTypes来接收,所以this.context的值为空对象
        console.log(this.context) // {}
    }
    render() {
        return (
            <Son />
        )
    }
}
// 父组件
export default class Parent extends Component {
    // 在父组件定义方法 getChildContext(),return返回的内容就是要传递给下级组件的context内容
    getChildContext() {
        return { color: "purple", text: "item text" };
    }
    // 需要通过静态属性childContextTypes来指定传递context参数的类型
    static childContextTypes = {
        color: PropTypes.string,
        text: PropTypes.string
    };
    render() {
        return (
            <Child />
        )
    }
}
郭炯韦个人博客 备案号: 豫ICP备17048833号-1
Top