class HTMLComment extends React.Component {
constructor(props) {
super(props);
this.ref$rootDiv = React.createRef();
this.node = window.document.createComment(props.text);
}
componentDidMount() {
if (this.ref$rootDiv && this.ref$rootDiv.current) {
let divElement = this.ref$rootDiv.current;
ReactDOM.unmountComponentAtNode(divElement);
this.ref$rootDiv.current.replaceWith(this.node);
}
}
componentDidUpdate(prevProps) {
if (prevProps.text !== this.props.text) {
this.node.textContent = this.props.text;
}
}
componentWillUnmount() {
this.node.remove();
}
render() {
return (React.createElement("div", { ref: this.ref$rootDiv, style: {
display: 'none',
} }));
}
}
const HTMLCommentWrapper = (props) => {
return (React.createElement(React.Fragment, null,
React.createElement(HTMLComment, { text: `<fragment data-reactid="">` }),
props.children,
React.createElement(HTMLComment, { text: `</fragment>` })));
};
const A = (props) => { return React.createElement("a", null, props.children); };
const B = (props) => { return React.createElement("b", null, props.children); };
const C = (props) => { return React.createElement("c", null, props.children); };
const D = (props) => { return React.createElement("d", null, props.children); };
const E = (props) => { return React.createElement("e", null, props.children); };
const App = () => {
return (React.createElement(A, null,
React.createElement(B, null),
React.createElement(HTMLCommentWrapper, null,
React.createElement(C, null),
React.createElement(D, null)),
React.createElement(E, null)));
};
let el$root = document.getElementById('react-app');
if (el$root) {
ReactDOM.render(React.createElement(App, null), el$root);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react-app"/>
outerHTML
魔法来用注释节点替换注入的元素,从而实现结果。好技巧!useEffect(() => { ref.current.outerHTML = \
<!--${text}-->`; }, [text]); return (<script ref={ref} type="text/placeholder" />);`https://dirask.com/posts/React-create-HTML-comment-comment-D7R861 - Dermot Doherty