[英]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. 我想通过调用super.render()
在ExtendedComponent
添加<p>
标签,问题是我不知道是否可以修改已经定义的jsx对象。 Ideal would be to just write parentTemplate + <p>Some paragraph</p>
, but that doesn't work. 理想的情况是只编写parentTemplate + <p>Some paragraph</p>
,但这是行不通的。
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. 就像评论中提到的azium一样,这并不常见。 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. 您必须将其包装在div中,因为react元素只能返回一个元素,而不能返回它们的列表。 parentTemplate
is just like any other jsx, but it's in a variable. parentTemplate
与其他jsx一样,但是都在一个变量中。 You use the {variableName}
syntax to add variables into the JSX. 您可以使用{variableName}
语法将变量添加到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')
);
Here ExtendedComponent
is a higher-order component rather than one that inherits from BaseComponent. 在这里, ExtendedComponent
是一个高阶组件,而不是从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! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.