目前,render方法只能返回单个元素/组件。看到: 这里
在该票据的讨论中,一些人建议在HTML注释中包装从React组件返回的多个元素,以便浏览器忽略包装组件,例如:
<A>
<B></B>
<Fragment>
<C></C>
<D></D>
</Fragment>
<E></E>
</A>
会呈现给:
<a>
<b></b>
<!--<fragment data-reactid="">-->
<c></c>
<d></d>
<!--</fragment>-->
<e></e>
</a>
但是如何实际创建一个只呈现HTML注释的组件?换句话说,上面例子中'fragment'组件的render函数如何看起来像?
这是我最近的一个项目中最终得到的结果:
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
class ReactComment extends Component {
static propTypes = {
text: PropTypes.string,
trim: PropTypes.bool
};
static defaultProps = {
trim: true
};
componentDidMount() {
let el = ReactDOM.findDOMNode(this);
ReactDOM.unmountComponentAtNode(el);
el.outerHTML = this.createComment();
}
createComment() {
let text = this.props.text;
if (this.props.trim) {
text = text.trim();
}
return `<!-- ${text} -->`;
}
render() {
return <div />;
}
}
export default ReactComment;
所以你可以像这样使用它:
<A>
<B></B>
<ReactComment text="<fragment>" />
<C></C>
<D></D>
<ReactComment text="</fragment>" />
<E></E>
</A>
编辑: 对于那些发现这个答案有用的人,结帐 这个答案 代替!
发布的问题不是要求React中的评论风格!
使用大括号,这样您就可以使用javascript注释 /* */
。
<a>
<b></b>
{/*<fragment data-reactid="">*/}
<c></c>
<d></d>
{/*</fragment>*/}
<e></e>
</a>
您计划这样做的方式不适用于简单的香草React解决方案。但是,您可以定义一个自定义Web组件,该组件可转换为HTML注释并从React包装器中返回。实现了一个示例组件 这里。有关在React中的用法,请参阅 这个网址。
2017年1月19日更新
所以这是未经测试的理论,但网络组件可能是这样的 -
```
/**
* <react-comment-sentinel> Web Component
*
* @usage
* <react-comment-sentinel sentinel="fragment"><div>Hello there!</div></react-comment-sentinel>
* @result
* <!-- <fragment> --><div>Hello there!</div><!-- </fragment> -->
*/
var proto = Object.create(HTMLElement.prototype, {
name: { get: function() { return 'React HTML Comment'; } },
createdCallback: { value: function() {
/**
* Firefox fix, is="null" prevents attachedCallback
* @link https://github.com/WebReflection/document-register-element/issues/22
*/
this.is = '';
this.removeAttribute('is');
} },
attachedCallback: { value: function() {
var tag = this.attributes("sentinel");
this.outerHTML = '<!-- <' + tag + '> -->' + this.innerHtml + '<!-- </' + tag + '> -->';
} }
});
document.registerElement('react-comment-sentinel', { prototype: proto });
```
请注意,内部子项是纯HTML,而不是React。但是,您可以尝试增强代码 支持React组件 太。