我正在尝试创建一些UI实用组件,并使用。这些实用程序旨在为HTML元素提供一些默认样式。
FullScreen
只是一个<div>
,它的高度是100vh
,宽度是100vw
。
所以我认为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
在props.style
道具中指定height: 100vh
和width: 100vw
的同时传递style
的正确方法是什么?
发布于 2022-01-26 06:22:38
HTMLDivElement
是div
元素的原生浏览器接口。但是,要将它用作react的div
的支柱类型,您必须将它封装在React.HTMLProps<...>
接口中。
进入Omit
部分,您需要省略ref
,因为您无法从道具中读取ref
。您需要将React.forwardRef
临时使用,并将其作为功能组件的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>
);
}
现在,如果您想在组件中使用它,那么可以使用它(不要忽略它)。但是,在将其扩展到props
元素中之前,一定要将其从div
中删除,因为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
https://stackoverflow.com/questions/70859033
复制相似问题