javascript - 与 TypeScript react : What type is render()?

标签 javascript reactjs typescript

我正在尝试将我的组件转换为 TypeScript。我可以为返回 HTML 的渲染指定什么类型?

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

最佳答案

我不知道当这个问题第一次被问到时它是否做到了,但是 React 有通过 @types/react 可用的类型。模块(现在)。 render 的返回类型是React.ReactNode定义如下:

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

您可以在 index.d.ts file 中找到这些不同子类型的详细信息在 DefinitelyTyped/DefinitelyTyped .

Can I specify any type for render, which returns HTML?

render不返回 HTML(这将是一个字符串)。来自 the documentation :

When called, it should examine this.props and this.state and return one of the following types:

  • React elements. Typically created via JSX. For example, <div /> and <MyComponent /> are React elements that instruct React to render a DOM node, or another user-defined component, respectively.
  • 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. See the documentation on portals for more details.
  • String and numbers. These are rendered as text nodes in the DOM.
  • Booleans or null. Render nothing. (Mostly exists to support return test && <Child /> pattern, where test is boolean.)

关于javascript - 与 TypeScript react : What type is render()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45073391/

相关文章:

javascript - 使用有意的 HTML 注入(inject)创建 HTML

javascript - highchart 通过在下拉列表中选择月份来更改图表

html - 如何在 ReactJS 中使用单选按钮?

reactjs - 通过 react-three-fibre 中的 Prop 传递纹理的 URL

javascript - 如何使用 HTML 元素属性将数据从 Blade.php 文件传递​​到 React 组件?

javascript - typescript 将字符串解析为数字组 345-67 以及包含单词和数字的文本

javascript - 如何根据多属性和多属性值显示/隐藏元素?

html - 类型错误 : onEmailBlur is not a function

typescript :是否可以创建指定长度的元组?

javascript - 如何打印带有黑色背景图像的白色文本