简体   繁体   中英

React: Child Components Without JSX

I want to create React components and add child components to it without the use of JSX . I tried the following:

class ChildComponent extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("p", {}, "hello world");
  }
}

class Component  extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("div", {}, ChildComponent);
  }
}

I also tried this

const childComponent = createReactClass({
  render: function() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("p", {}, "hello world");
  }
});

const component = createReactClass({
  render: function() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("div", {}, childComponent);
  }
});

And I get this error:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

All you need to do to create element is to pass the third parameter as the React element instead of a normal argument. Make use of React.createElement to create an element out of the react ChildComonent class

class ChildComponent extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("p", {}, "hello world");
  }
}

class Component extends React.Component {
  render() {
    const template = Object.assign({}, this.state, this.props);
    return React.createElement("div", {}, React.createElement(ChildComponent));
  }
}

Working codesandbox

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