我使用相同的 jsx 渲染服务器端和客户端。我需要一些只有 html 的元素,不需要 data-reactid。 (例如,纯 html jsx 布局有一些动态变量,但不需要 data-reactid)。
除了我可以重用包含 data-reactid 的服务器端渲染 dom,并且不需要重新渲染 View 。
另一个元素有 data-reactid ,它不需要reactjs重新渲染。
无法使用 shouldComponentUpdate
,因为“renderToString”方法不会调用 shouldComponentUpdate
。
我不异常(exception),我应该渲染两个具有不同功能的元素(例如renderToStaticMarkup、renderToString)并将其组合起来,因为该元素可能被许多元素包含。当元素较多时,渲染拆分和合并可能会导致错误。
这是我的幻想:
在这种情况下,我希望 {this.props.children} 有 data-reactid,但外部 html 和 buddy (DefaultLayout) 没有。
class DefaultLayout extends React.Component{
if (typeof window !== 'undefined') {
return (
<div>{this.props.children}</div>
);
}
return (
<html>
<head>
</head>
<body>
<div id="container" className='container'>
<div>{this.props.children}</div>
</div>
<script src='/js/index.js'type='text/javascript'></script>
</body>
</html>
);
}
};
DefaultLayout.noNeedDiffCompoment = true;
export default DefaultLayout;
或者一个新的纯html组件
class DefaultLayout extends React.PureHtmlComponent{
if (typeof window !== 'undefined') {
return (
<div>{this.props.children}</div>
);
}
return (
<html>
<head>
</head>
<body>
<div id="container" className='container'>
<div>{this.props.children}</div>
</div>
<script src='/js/index.js'type='text/javascript'></script>
</body>
</html>
);
}
};
export default DefaultLayout;
我可以轻松使用这个布局,并且在客户端和服务器端不会出错。
class Somepage extends React.Component {
constructor(props) {
super(props);
}
render(){
return (
<DefaultLayout>
<h1>Hello world</h1>
</DefaultLayout>
);
}
};
如果我按照上面的方式编写,渲染函数可以自动交换渲染函数来渲染元素。
有没有像这样优雅的解决方案?
最佳答案
在这种情况下,您应该使用著名的 dangerouslySetInnerHTML
而不是 props.children
。
没有其他解决方案。
const DefaultLayout = ({html}) => (
<html>
<head>
</head>
<body>
<div id="container" className='container' dangerouslySetInnerHTML={html} />
<script src='/js/index.js'type='text/javascript'></script>
</body>
</html>
);
export default DefaultLayout;
还有...
const html = renderToString(<App />);
return renderToStaticMarkup(<DefaultLayout html={html} />);
关于javascript - ReactJS有自动切换渲染功能吗? (渲染到静态标记,渲染到字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34941646/