繁体   English   中英

有条件地传播道具并获得有关道具丢失的 TS 错误

[英]Spreading props conditionally and getting a TS error regarding props missing

我正在尝试有条件地传播一些道具,但出现错误

类型 '{ activeStyles: { [key: string]: string; }; onClick:()=>无效; 文本:字符串; } | { inactiveStyles: { [key: string]: string; }; onClick:()=>无效; 文本:字符串; }' 不可分配给类型 'IntrinsicAttributes & BtnProps'。 类型 '{ activeStyles: { [key: string]: string; }; onClick:()=>无效; 文本:字符串; }' 缺少“BtnProps”类型的以下属性:bg、颜色

这是我的组件:

interface BtnProps {
  bg: string
  text: string
  color: string
  onClick: () => void
}

export const Toggle: React.FC = (): JSX.Element => {
  const [btnClicked, setBtnClicked] = useState(true)

  const MyBtn = ({ text, bg, color, onClick }: BtnProps) => {
    return <Button {...{ bg, color, onClick, size: 'sm' }}>{text}</Button>
  }

  const activeStyles: { [key: string]: string } = { color: 'white', bg: 'blue.500' }
  const inactiveStyles: { [key: string]: string } = { color: 'blue.500', bg: 'white' }

  console.log(activeStyles) // { color: 'white', bg: 'blue.500' }

  return (
    <Center d="flex">
      <MyBtn
        {
          ...{
            onClick: () => setBtnClicked(true),
            text: 'document',
            ...(btnClicked ? { ...activeStyles } : { ...inactiveStyles }),
          }
        }
      />
    </Center>
  )
}

为了让它工作,我应该这样做,我认为是一样的:

  <MyBtn
    {...{
      onClick: () => setBtnClicked(true),
      text: 'Document',
      ...(btnClicked ? { color: 'white', bg: 'blue.500' } : { color: 'blue.500', bg: 'white' }),
    }}
  />

有什么想法吗?

您必须从DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>,HTMLButtonElement>扩展您的界面,以便它可以具有默认按钮的属性。 完整的代码是

import React, {
    ButtonHTMLAttributes,
    DetailedHTMLProps,
    FunctionComponent,
    HTMLProps,
} from "react";

interface BtnProps extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>,HTMLButtonElement>  {
  bg: string
  text: string
  color: string
  onClick: () => void
}
  <MyBtn
      onClick={() => setBtnClicked(true)}
      text="document"
      {...(btnClicked ? activeStyles : inactiveStyles)}
   />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM