Typescript React - 类型"字符串"不能分配给类型"外观"



我正在尝试使用 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: 100vhwidth: 100vw的同时,传递props.style的正确方法是什么?

HTMLDivElementdiv元素的本机浏览器界面。但是,要将其用作 reactdiv的 prop 类型,您必须将其包装React.HTMLProps<...>接口中。

来到Omit部分,您需要省略ref因为您无法从道具中读取ref。您需要使用React.forwardRefHOC 并将其作为功能组件的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

相关内容

最新更新