简体   繁体   English

用TypeScript做出反应:render()是什么类型?

[英]React with TypeScript: What type is render()?

I'm trying to convert my components to TypeScript. 我正在尝试将我的组件转换为TypeScript。 What type can I specify for render, which returns HTML? 我可以指定哪种类型的渲染,返回HTML?

class Component extends React.Component {
    render() {
        return (
            <div>
                ...some HTML...
            </div>
        );       
    }
}

I don't know whether it did when this question was first asked, but React has types available via the @types/react module (now). 我不知道第一次问这个问题时它是否这样做,但是React通过@types/react模块(现在)有可用的@types/react The return type of render is React.ReactNode which is defined like this: render的返回类型为React.ReactNode ,其定义如下:

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

You can find the details of those various subtypes in the index.d.ts file at DefinitelyTyped/DefinitelyTyped . 您可以在index.d.ts文件DefinitelyTyped/DefinitelyTyped找到这些子类型的详细信息。

Can I specify any type for render, which returns HTML? 我可以指定任何返回HTML的渲染类型吗?

render doesn't return HTML (which would be a string). render不返回HTML(这将是一个字符串)。 From the documentation : 文档中

When called, it should examine this.props and this.state and return one of the following types: 调用时,它应检查this.props和this.state并返回以下类型之一:

  • React elements . 反应元素 Typically created via JSX. 通常通过JSX创建。 For example, <div /> and <MyComponent /> are React elements that instruct React to render a DOM node, or another user-defined component, respectively. 例如, <div /><MyComponent />是React元素,分别指示React渲染DOM节点或另一个用户定义的组件。
  • Arrays and fragments . 数组和片段 Let you return multiple elements from render. 让您从渲染返回多个元素。 See the documentation on fragments for more details. 有关更多详细信息,请参见有关片段的文档。
  • Portals . 门户网站 Let you render children into a different DOM subtree. 让您将子级渲染到另一个DOM子树中。 See the documentation on portals for more details. 有关更多详细信息,请参见门户网站上的文档。
  • String and numbers . 字符串和数字 These are rendered as text nodes in the DOM. 这些在DOM中呈现为文本节点。
  • Booleans or null . 布尔值或null Render nothing. 什么都不渲染。 (Mostly exists to support return test && <Child /> pattern, where test is boolean.) (大多数情况下都支持return test && <Child />模式,其中test为布尔值。)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM