简体   繁体   English

在 Typescript 中使用 ReactDomServer.renderToString 的正确方法是什么

[英]What's the proper way of using ReactDomServer.renderToString with Typescript

I'm working on a Typescript app that does server-side rendering and I'm having trouble understanding the usage of ReactDomServer.renderToString and ReactDom.hydrate , specifically the type of arguments they sould receive.我正在开发一个执行服务器端渲染的 Typescript 应用程序,但我无法理解ReactDomServer.renderToStringReactDom.hydrate的用法,特别是它们应该接收的参数类型。

I've found several examples (using JS) passing a JSX tag as the argument the following way:我发现了几个示例(使用 JS)通过以下方式传递 JSX 标记作为参数:

ReactDomServer.renderToString(<ExampleComponent exampleProp="anyValue" />);

But when I try this on Typescript I get the following error:但是当我在 Typescript 上尝试这个时,我收到以下错误:

Conversion of type 'RegExp' to type 'ExampleComponent' may be a mistake because neither type sufficiently overlaps with the other.将 'RegExp' 类型转换为 'ExampleComponent' 类型可能是错误的,因为这两种类型与另一种类型都没有足够的重叠。 If this was intentional, convert the expression to 'unknown' first.如果这是故意的,请先将表达式转换为“未知”。

The way I got it working is by invoking React.createElement on my Component:我让它工作的方式是在我的组件上调用React.createElement

ReactDomServer.renderToString(
  React.createElement(ExampleComponent, {exampleProp: anyValue})
)

Do you have to call React.createElement on the component you want to render (if so, why)?您是否必须在要渲染的组件上调用React.createElement (如果是,为什么)? Or is it a bug/misconfiguration on my side?还是我这边的错误/配置错误?

我的问题是文件扩展名是.ts ,打字稿需要是.tsx才能正确编译 JSX。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReactDOMServer.renderToString不是函数 - ReactDOMServer.renderToString is not a function onClick处理程序没有注册ReactDOMServer.renderToString - onClick handler not registering with ReactDOMServer.renderToString JavaScript:如何使用 ReactDOMServer.renderToString 格式化 str.replace,使用捕获的元素作为道具 - JavaScript: How to format a str.replace with ReactDOMServer.renderToString, using a captured element as a prop 使用 ReactDOMServer.renderToString 将 gatsby-image 注入从 markdown 创建的 html - Injecting gatsby-image into html created from markdown using ReactDOMServer.renderToString typescript 的正确使用方法? - Proper way of using typescript? 实现此自定义打字稿模块的正确方法是什么? - what's the proper way to implement this custom typescript module? 使用Javascript的window.opener的正确方法是什么? - What's the proper way of using Javascript's window.opener? 使用 Angular 在 AWS 上命中/使用 API 的正确方法是什么? - What's the proper way to hit/consume APIs on AWS using Angular? 在Object.create中使用属性描述符的正确方法是什么? - What's the proper way of using property descriptors in Object.create? <a>用Javascript / JQuery</a>替换` <a>`</a>的正确方法是<a>什么?</a> - What's the proper way to replace `<a>` using Javascript/JQuery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM