首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >类型记录反应-“string”类型不能用于键入“出现”

类型记录反应-“string”类型不能用于键入“出现”
EN

Stack Overflow用户
提问于 2022-01-26 05:39:29
回答 1查看 409关注 0票数 1

我正在尝试创建一些UI实用组件,并使用。这些实用程序旨在为HTML元素提供一些默认样式。

FullScreen只是一个<div>,它的高度是100vh,宽度是100vw

所以我认为FullSreenProps应该扩展HTMLDivElement。但是,当我将props.style扩展到style属性中时,我会得到一个类型错误:

代码语言:javascript
运行
复制
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组件:

代码语言:javascript
运行
复制
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: 100vhwidth: 100vw的同时传递style的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-26 06:22:38

HTMLDivElementdiv元素的原生浏览器接口。但是,要将它用作react的div的支柱类型,您必须将它封装在React.HTMLProps<...>接口中。

进入Omit部分,您需要省略ref,因为您无法从道具中读取ref。您需要将React.forwardRef临时使用,并将其作为功能组件的second参数。

而且,as是一个特殊的支柱,我们可以用它来替换组件。就像。<Typography as="h1">Hi there</Typography><Typography as="h4">Hi there</Typography>等,在Typography组件中,您可以执行以下操作:

代码语言:javascript
运行
复制
const Typography = (props) => {
  const {as: Component, children, ...other} = props;
  return (
    <Component {...other}>{children}</Component>
  );
}

现在,如果您想在组件中使用它,那么可以使用它(不要忽略它)。但是,在将其扩展到props元素中之前,一定要将其从div中删除,因为div不接受它。

您可以尝试以下方法:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70859033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档