此问题只能在 babel 中重现(使用 babel-runtime-6.26.0)。
具有以下结构
class Foo extends React.Component {
// ...
}
class Bar extends React.Component {
render() {
return this.props.component();
}
}
// somewhere:
<Bar component={Foo} />
一般来说对我有用,但是当切换到 babel 时,我收到错误消息:
类型错误:无法在
。我读到这是符合规范的行为,但它确实可以在 babel 环境之外工作。(classCallCheck.js:7)
中将类作为函数调用
顺便说一句,如果我使用功能无状态组件,它当然可以工作。但我不能保证我的库的使用者提供这样的组件而不是基于类的组件。
- 如何使用 babel 来解决这个问题?
- 是否有不同的模式可用于通过属性传递组件?我相信通过 props 向组件传递类/类构造函数是常见的做法。
最佳答案
组件可以是函数或类。没有 new
就无法调用 ES6 类,至少是符合规范的类(包括 native 类和 Babel 类)。
这不是问题,因为组件不应手动实例化。函数和类组件都将由 ReactDOM.render
正确处理:
class Bar extends React.Component {
render() {
const Component = this.props.component;
return <Component/>;
}
}
关于javascript - 如何传递扩展 React.Component 的类作为属性来渲染它(使用 babel)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673268/