gpt4 book ai didi

javascript - 有条件地传播 Prop 并获得有关 Prop 丢失的 TS 错误

转载 作者:行者123 更新时间:2023-12-04 08:10:20 24 4
gpt4 key购买 nike

我试图有条件地传播一些 Prop ,但出现错误

Type '{ activeStyles: { [key: string]: string; }; onClick: () => void; text: string; } | { inactiveStyles: { [key: string]: string; }; onClick: () => void; text: string; }' is not assignable to type 'IntrinsicAttributes & BtnProps'.Type '{ activeStyles: { [key: string]: string; }; onClick: () => void; text: string; }' is missing the following properties from type 'BtnProps': bg, color


这是我的组件:
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
}

关于javascript - 有条件地传播 Prop 并获得有关 Prop 丢失的 TS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66004055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com