[英]How to pass a class extending React.Component as a property to render it (using babel)?
This issue is only reproducable in babel (using babel-runtime-6.26.0). 此问题仅在babel中可重现(使用babel-runtime-6.26.0)。
Having the following structure 具有以下结构
class Foo extends React.Component {
// ...
}
class Bar extends React.Component {
render() {
return this.props.component();
}
}
// somewhere:
<Bar component={Foo} />
worked and works for me in general, but when switching to babel I get the error message: TypeError: Cannot call a class as a function
in (classCallCheck.js:7)
. 总的来说对我来说是
(classCallCheck.js:7)
,但是在切换到babel时,我收到错误消息: TypeError: Cannot call a class as a function
在(classCallCheck.js:7)
TypeError: Cannot call a class as a function
。 I've read that this is spec compliant behavior, but it does work outside of the babel environment. 我已经读到这是符合规范的行为,但是它确实在babel环境之外起作用。
Btw, if I use functional stateless components it works, of course. 顺便说一句,如果我使用功能性无状态组件,那当然可以。 But I can't guarantee that the consumer of my lib is providing such a component and not a class based one.
但是我不能保证我的库的使用者提供了这样的组件,而不是基于类的组件。
A component can be either a function or a class. 组件可以是函数或类。 And ES6 classes cannot be called without
new
, at least the ones that are spec-compliant (this includes native and Babel classes). 而且,如果没有
new
,则不能调用ES6类,至少要符合规范(包括本地类和Babel类)。
This is not a problem since components shouldn't be instantiated manually. 这不是问题,因为不应手动实例化组件。 Both function and class components will be properly handled by
ReactDOM.render
: 函数和类组件都将由
ReactDOM.render
正确处理:
class Bar extends React.Component {
render() {
const Component = this.props.component;
return <Component/>;
}
}
Try using React.createElement(this.props.component, props)
instead. 尝试
React.createElement(this.props.component, props)
使用React.createElement(this.props.component, props)
。
Here's a working example: 这是一个工作示例:
class Foo extends React.Component {
render() { return "Foo" }
}
class Bar extends React.Component {
render() {
return React.createElement(this.props.component, {})
}
}
ReactDOM.render(
<Bar component={Foo} />,
document.getElementById('root')
);
https://codepen.io/anon/pen/QQGQYZ https://codepen.io/anon/pen/QQGQYZ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.