简体   繁体   English

React:没有JSX的子组件

[英]React: Child Components Without JSX

I want to create React components and add child components to it without the use of JSX . 我想创建React组件并在不使用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. 警告:函数作为React子函数无效。 This may happen if you return a Component instead of from render. 如果返回Component而不是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. 创建元素所需要做的就是将第三个参数作为React元素而不是普通参数传递。 Make use of React.createElement to create an element out of the react ChildComonent class 利用React.createElement从反应的ChildComonent类中创建一个元素

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 工作代码盒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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