javascript ES6 中的 childContextType
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32078493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
childContextTypes in ES6
提问by Chris G.
How would you write the object childContextTypes in ES6?
你会如何在 ES6 中编写对象 childContextTypes?
var A = React.createClass({
childContextTypes: {
name: React.PropTypes.string.isRequired
},
getChildContext: function() {
return { name: "Jonas" };
},
render: function() {
return <B />;
}
});
回答by cutemachine
Since you are using Babel anyway, you can use static
(ES7) in your code like this:
由于您无论如何都在使用 Babel,因此您可以static
在代码中使用(ES7),如下所示:
export default class A extends React.Component {
static childContextTypes = {
name: React.PropTypes.string,
}
getChildContext() {
return { name: "Jonas" }
}
render() {
return <B />
}
}
More info: React on ES6+
更多信息:在 ES6+ 上反应
回答by evanbikes
The issue is that childContextTypes
needs to be defined on the "class", which is what static
does. So these two solutions seem to work:
问题是childContextTypes
需要在“类”上定义,这是什么static
。所以这两个解决方案似乎有效:
class A extends React.Component {
constructor() {
super(...arguments);
this.constructor.childContextTypes = {
name: React.PropTypes.string.isRequired
};
}
}
Or
或者
class A extends React.Component {
}
A.childContextTypes = {
name: React.PropTypes.string.isRequired
};
回答by Inessa Pokromkina
try this:
试试这个:
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>;
}
}
Source code form here: React ES6 Context
源代码形式在这里: React ES6 Context
回答by Chris G.
The solution was to move "childContextTypes" out of the class:
解决方案是将“childContextTypes”移出类:
class { .,, };
childContextTypes() {..}
班级 { 。,, };
childContextTypes() {..}
Or wait for ES7 to have static properties.
或者等 ES7 有静态属性。
回答by Nick Perkins
If you are using Coffeescript...
如果您使用的是 Coffeescript...
change
改变
childContextTypes:
to
到
@childContextTypes: