简体   繁体   中英

How to contatenate React JSX objects

I would like to add <p> tag in ExtendedComponent by calling super.render() , Problem is I don't know whether it is possible to modify already defined jsx object. Ideal would be to just write parentTemplate + <p>Some paragraph</p> , but that doesn't work.

class BaseComponent extends React.Component {
  get title() {
    return 'I am base component';
  }

  render() {
    return <h1>Hello {this.title}</h1>;
  }
}

class ExtendedComponent extends BaseComponent {
  get title() {
    return 'I am extended component';
  }

  render() {
    var parentTemplate = super.render();
    // append <p>Some paragraph</p> to parentTemplate
    return parentTemplate;
  }
}

ReactDOM.render(
  <ExtendedComponent />,       
  document.getElementById('test')
);

Like azium mentioned in the comments, this is not common to do with react. However, if you need to do it, it can be accomplished like this:

render() {
  var parentTemplate = super.render();
  // append <p>Some paragraph</p> to parentTemplate 
  return <div>{parentTemplate}<p>Some paragraph</p></div>;
}

You have to wrap it inside a div since a react element only can return one element, not a list of them. parentTemplate is just like any other jsx, but it's in a variable. You use the {variableName} syntax to add variables into the JSX.

Another way to do this, which is more "react"-like:

class BaseComponent extends React.Component {
  render() {
    return <h1>Hello {this.props.title}</h1>;
  }
}
BaseComponent.propTypes = {
  title: React.PropTypes.string
};
BaseComponent.defaultProps = {
  title: 'I am base component'
};

class ExtendedComponent extends React.Component {
  render() {
    return (
      <div>
        <BaseComponent title="I am extended component"/>
        <p>Some paragraph</p>
      </div>
    );
  }
}

ReactDOM.render(
  <ExtendedComponent />,       
  document.getElementById('test')
);

JSFiddle

Here ExtendedComponent is a higher-order component rather than one that inherits from BaseComponent. Most of the time this is a seperation of concerns that is easier to reason about, and most react apps are built this way rather than on inheritation.

Hope this helps!

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