我正在尝试将我的组件转换为 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/