gpt4 book ai didi

javascript - 如何传递一个扩展 React.Component 的类作为属性来渲染它(使用 babel)?

转载 作者:行者123 更新时间:2023-11-29 18:57:36 26 4
gpt4 key购买 nike

这个问题只能在 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 时,我收到错误消息:TypeError:无法将类作为函数调用(classCallCheck.js:7) 中。我读到过这是符合规范的行为,但它确实可以在 babel 环境之外工作。

顺便说一句,如果我使用功能性无状态组件,它当然可以工作。但我不能保证我的库的使用者提供的是这样的组件,而不是基于类的组件。

  • 如何使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com