Я потратил более 10 часов, чтобы наконец воспроизвести.
import * as React from 'react'
import * as ReactDomServer from 'react-dom/server'
import * as ReactDom from 'react-dom'
import * as RehypeReact from 'rehype-react'
import * as unified from 'unified'
const Youtube = props => {
return <p data-test="Youtube">test</p>
}
const P = props => {
return <p data-test="ppp">{props.children}</p>
}
const options = {
createElement: React.createElement,
components: {
youtube: Youtube,
p: P,
},
}
var processor = unified().use(RehypeReact, options)
export const MarkdownRenderer: React.FC<{}> = props => {
const ast = {
type: 'root',
children: [
{
type: 'element',
tagName: 'p',
properties: {},
children: [
{
type: 'element',
tagName: 'youtube',
children: [],
},
],
},
{
type: 'text',
value: '\n',
},
{
type: 'element',
tagName: 'p',
properties: {},
children: [
{
type: 'text',
value: 'xxxx',
},
],
},
{
type: 'element',
tagName: 'p',
properties: {},
children: [
{
type: 'text',
value: 'yyy',
},
],
},
],
data: {
quirksMode: false,
},
}
const output = processor.stringify(ast)
console.log(`>>>`, ReactDomServer.renderToString(output))
// Outputs:
// <div data-reactroot="">
// <p data-test="ppp"><p data-test="Youtube">test</p></p>
// <p data-test="ppp">xxxx</p>
// <p data-test="ppp">yyy</p>
// </div>
// But the dom in the browser is
// <div>
// <p data-test="ppp"><p data-test="Youtube">test</p></p>
// <p data-test="Youtube">xxxx</p>
// <p>yyy</p>
// </div>
return output
}
setTimeout(() => {
// here renders correctly
// <div>
// <p data-test="ppp"><p data-test="Youtube">test</p></p>
// <p data-test="ppp">xxxx</p>
// <p data-test="ppp">yyy</p>
// </div>
ReactDom.render(<MarkdownRenderer />, document.body)
}, 5000)
Код с сервера в порядке, только первый рендер испорчен. Также можно сменить страницу и вернуться назад. кодовый блок