我正在尝试使用 React Typescript 创建一些 UI 实用程序组件。这些实用程序旨在为 HTML 元素提供一些默认样式。
FullScreen
只是一个高度为100vh
,宽度为100vw
的<div>
。
所以我认为FullSreenProps
应该扩展HTMLDivElement
.但是当我props.style
分散到 style 属性中时,我收到一个类型错误:
Type '{ width: string; height: string; accentColor: string; alignContent: string; alignItems: string; alignSelf: string; alignmentBaseline: string; all: string; animation: string; animationDelay: string; ... 443 more ...; [Symbol.iterator](): IterableIterator<...>; }' is not assignable to type 'CSSProperties'.
Types of property 'appearance' are incompatible.
Type 'string' is not assignable to type 'Appearance'.ts(2322)
下面是FullScreen
组件:
import React, { useState, useEffect, useMemo } from 'react';
interface FullScreenProps extends HTMLDivElement{}
const FullScreen = (props: FullScreenProps): JSX.Element => {
return (
<div
{...props}
style={
{
...props.style,
width: "100vw",
height: "100vh",
}
}
>
</div>
);
}
export default FullScreen
在style
道具中指定height: 100vh
和width: 100vw
的同时,传递props.style
的正确方法是什么?
HTMLDivElement
是div
元素的本机浏览器界面。但是,要将其用作 reactdiv
的 prop 类型,您必须将其包装React.HTMLProps<...>
接口中。
来到Omit
部分,您需要省略ref
因为您无法从道具中读取ref
。您需要使用React.forwardRef
HOC 并将其作为功能组件的second
参数获取。
而且,as
是一个特殊的道具,我们可以用来替换组件。例如。<Typography as="h1">Hi there</Typography>
或<Typography as="h4">Hi there</Typography>
等,在Typography
组件中,您可以执行以下操作:
const Typography = (props) => {
const {as: Component, children, ...other} = props;
return (
<Component {...other}>{children}</Component>
);
}
现在,如果你想在你的组件中使用它,那么你可以(不要省略它)。但是,在将它们分散到div
元素之前,请务必将其从props
中删除,因为div
不接受它。
您可以尝试以下操作:
import React from 'react';
interface FullScreenProps extends Omit<React.HTMLProps<HTMLDivElement>, 'as' | 'ref'> {}
const FullScreen = (props: FullScreenProps): JSX.Element => {
return (
<div
{...props}
style={
{
...(props.style || {}),
width: "100vw",
height: "100vh",
}
}
>
</div>
);
}
export default FullScreen