ChildContextTypes в ES6

Как вы могли бы написать объект childContextTypes в ES6?

var A = React.createClass({

    childContextTypes: {
         name: React.PropTypes.string.isRequired
    },

    getChildContext: function() {
         return { name: "Jonas" };
    },

    render: function() {
         return <B />;
    }
});

Ответы

Ответ 1

Поскольку вы все равно используете Babel, вы можете использовать static (ES7) в своем коде следующим образом:

export default class A extends React.Component {

  static childContextTypes = {
    name: React.PropTypes.string,
  }

  getChildContext() {
    return { name: "Jonas" }
  }

  render() {
    return <B />
  }
}

Дополнительная информация: Реагировать на ES6 +

Ответ 2

Проблема заключается в том, что childContextTypes должен быть определен в "классе", что и делает static. Итак, эти два решения работают:

class A extends React.Component {
  constructor() {
    super(...arguments);

    this.constructor.childContextTypes = {
      name: React.PropTypes.string.isRequired
    };
  }
}

или

class A extends React.Component {

}

A.childContextTypes = {
  name: React.PropTypes.string.isRequired
};

Ответ 3

Решением было перемещение "childContextTypes" из класса:

class {., };

childContextTypes() {..}

Или подождите, пока ES7 будет иметь статические свойства.

Ответ 4

попробуйте следующее:

import React, { PropTypes } from 'react';

export default class Grandparent extends React.Component {
  static childContextTypes = {
    getUser: PropTypes.func
  };

   getChildContext() {
    return {
      getUser: () => ({ name: 'Bob' })
    };
  }

  render() {
    return <Parent />;
  }
}

class Parent extends React.Component  {
  render() {
    return <Child />;
  }
}

class Child extends React.Component {
  static contextTypes = {
    getUser: PropTypes.func.isRequired
  };

  render() {
    const user = this.context.getUser();
    return <p>Hello {user.name}!</p>;
  }
}

Ответ 5

Если вы используете Coffeescript...

изменить

childContextTypes:

к

@childContextTypes: