简体   繁体   中英

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).

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) . I've read that this is spec compliant behavior, but it does work outside of the babel environment.

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.

  • How can I approach this using babel?
  • Is there a different pattern to use to pass components via properties? I believe it's common practice to pass in classes/class constructors via props to components.

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).

This is not a problem since components shouldn't be instantiated manually. Both function and class components will be properly handled by ReactDOM.render :

class Bar extends React.Component {
  render() {
    const Component = this.props.component;
    return <Component/>;
  }
}

Try using React.createElement(this.props.component, props) instead.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM