繁体   English   中英

React:没有JSX的子组件

[英]React: Child Components Without JSX

我想创建React组件并在不使用JSX情况下向其添加子组件。 我尝试了以下方法:

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);
  }
}

我也尝试过这个

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);
  }
});

我收到这个错误:

警告:函数作为React子函数无效。 如果返回Component而不是render,则可能会发生这种情况。 或许你打算调用这个函数而不是返回它。

创建元素所需要做的就是将第三个参数作为React元素而不是普通参数传递。 利用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));
  }
}

工作代码盒

暂无
暂无

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

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