如何在React中呈现HTML注释? [英] How to render a HTML comment in React?

查看:820
本文介绍了如何在React中呈现HTML注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,render方法只能返回单个元素/组件。请参阅: here

Currently the render method can only return a single element/component. See: here

在该票下的讨论有些建议在HTML注释中包含从React组件返回的多个元素,以便浏览器忽略包装组件,例如:

In the discussion under that ticket some suggest to wrap multiple elements returned from a React component in a HTML comment so that the wrapping component is ignored by the browser, e.g.:

<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'组件的渲染函数如何看起来像?

But how to actually create a component that renders just HTML comment? In other words, how the render function of the 'fragment' component in the example above could look like?

推荐答案

这就是我最近在最近的一个项目中有:

This is what I have ended up with in one of my recent projects:

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中呈现HTML注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆