React `context` is always an empty object

I am trying to set the context in my React application, but for some reason I cannot get it contextfrom the children. This is the parent class:

import React from 'react'
import MenuBar from './MenuBar.js'

export default class App extends React.Component {

  static childContextTypes = {
    prop:    React.PropTypes.bool
  };

  getChildContext(){
    return {
      prop: true
    }
  }

  render() {
    return (
      <div>
        <MenuBar />
      </div>  
    )
  }

}

And here is my class of children:

import React, { Component } from 'react';

export default class MenuBar extends Component {

  constructor(props, context){
    super(props,context)
    console.log(this.context)
    console.log(context)
  }

  render() {
    console.log(this.context)
    return (
      <div>MenuBar</div>
    );
  }
}

Everyone console.logreturns an empty object, what am I doing wrong?

+4
source share
2 answers

Welcome to stack overflow :)

Context is mainly used by library authors, such as React Router and Redux - two widely used React libraries - currently rely on context. Here is a good summary written by Dan Abramov (author of Redux): fooobar.com/questions/89214 / ...

- , :

static contextTypes = {
  prop: React.PropTypes.bool
};

: http://codepen.io/PiotrBerebecki/pen/LRLgJP, - .

class App extends React.Component {
  static childContextTypes = {
    prop: React.PropTypes.bool
  };

  getChildContext() {
    return {prop: true};
  }
  render() {
    return <MenuBar/ >;
  }
}


class MenuBar extends React.Component {
  constructor(props, context) {
    super(props, context);
    console.log('in constructor', context.prop) // logs: true
  }

  static contextTypes = {
    prop: React.PropTypes.bool
  };

  render() {
    console.log('in render', this.context.prop) // logs: true
    return (
      <div>MenuBar</div>
    );
  }
}


ReactDOM.render(
  <App />,
  document.getElementById('app')
);

React v15.5 PropTypes React.PropTypes PropTypes :

import PropTypes from 'prop-types';

. https://reactjs.org/docs/typechecking-with-proptypes.html.

+10

- . API, , .

, prop.

<MenuBar myProp="hello"/>

MenuBar

 constructor(props, context){
    super(props,context)
    console.log(this.props.myProp) //prints 'hello'
  }
-1

Source: https://habr.com/ru/post/1656135/


All Articles