ES6中的childContextTypes

时间:2015-08-18 17:02:49

标签: javascript reactjs ecmascript-6 es2015

你如何在ES6中编写对象childContextTypes?

var A = React.createClass({

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

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

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

5 个答案:

答案 0 :(得分:22)

由于您仍在使用Babel,因此您可以在代码中使用static(ES7),如下所示:

export default class A extends React.Component {

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

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

  render() {
    return <B />
  }
}

更多信息:React on ES6+

答案 1 :(得分:13)

The issue is that import React, { Component } from 'react'; import ReactDOM from 'react-dom'; needs to be defined on the "class", which is what childContextTypes does. So these two solutions seem to work:

static

Or

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

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

答案 2 :(得分:0)

解决方案是移动&#34; childContextTypes&#34;课外:

  

class {   。,,   };

     

childContextTypes(){..}

或者等待ES7拥有静态属性。

答案 3 :(得分:0)

试试这个:

&#13;
&#13;
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>;
  }
}
&#13;
&#13;
&#13;

此处的源代码表: React ES6 Context

答案 4 :(得分:-1)

如果你正在使用Coffeescript ......

变化

childContextTypes:

@childContextTypes: