大佬教程收集整理的这篇文章主要介绍了如何将 Typescript 类型设置为字符串或 HTML 元素?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将 Typescript 类型设置为字符串或 HTML 元素?应该很简单,但目前似乎找不到任何答案。
基本上我想给“标题”道具一个字符串或 HTML。
<Dialog
title={<div>some HTML</div>}
</Dialog>
<Dialog
title={"Some String"}
</Dialog>
export type DialogProps = {
title?: Element | String | undefined;
};
您需要类型 React.ReactNode
。这包括 JSX.Element
以及 String
、number
、undefined
等。
这是 type definitions 的相关块:
type ReactText = String | number;
type ReactChild = ReactElement | ReactText;
interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | Boolean | null | undefined;
模棱两可的 Element
如果您只使用类型 Element
而不带前缀,那么您会从 lib.dom.ts
获得定义。 React 中包含的 JSX
命名空间对 JSX.Element
有自己的定义。
您示例中的 <div>some HTML</div>
是 JSX.Element
,实际上不能分配给 Element
类型。
function requireSELER_895_11845@ent(el: Element) {}
requireSELER_895_11845@ent(<div>some HTML</div>); // error
“JSX.Element”类型的参数不可分配给“Element”类型的参数。
“元素”类型缺少“元素”类型中的以下属性:attributes、classList、className、clientHeight 和 123 个更多。
Typescript Playground Link
,您可以将道具类型设置为界面:
interface DialogProps {
title: JSX.Element | String
}
interface State {}
class Dialog extends React.Component<DialogProps,State> {
...
}
@H_675_72@
以上是大佬教程为你收集整理的如何将 Typescript 类型设置为字符串或 HTML 元素?全部内容,希望文章能够帮你解决如何将 Typescript 类型设置为字符串或 HTML 元素?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。