TS的新手,不得不说错误不是很友好。
我试图将一个钩子函数传递给组件作为道具,并将其添加到我的界面中,但出现了我无法理解的错误。
没有重载匹配此调用。 重载1,共2个,'((props:Pick,HTMLButtonElement>,“ form” | ... 264更多... |“ onTransitionEndCapture”>&{...;}&IButtonProps,“ form” | ... 267更多... |“ setActivity”>&Partial <...>,“表单” | ... 267更多... |“ setActivity”>&{...;}&{...;}):ReactElement <...>',给出了以下错误。 类型'{children:string | type中缺少属性'setActivity' (字符串和{})| (字符串和ReactElement ReactElement组件)>)| (新(props:任何)=> Component <...>)>)| (字符串和ReactNodeArray)| (string&ReactPortal); active:布尔值; onClick:()=>功能; }”,但在类型“ Pick,HTMLButtonElement>,“表单” | ... 264更多... | “ onTransitionEndCapture”>&{...; }和IButtonProps,“表单” | ... 267更多... | “ setActivity”>&Partial <...>,“表单” | ... 26
我已经尝试了一些阅读的方法,例如将方法放入匿名函数中并将我的onclick设置为(e: React.MouseEvent) => void
,但似乎没有任何效果。从我的代码中,我觉得我做的一切正确,但显然做不到。
这是我的组件:
interface IButtonProps {
children: string,
active: Boolean,
setActivity: Function,
onClick: (e: React.MouseEvent) => void,
}
// Styling
const Button = styled.button<IButtonProps>`
${({ theme }) => `
border: ${theme.TabsBorder};
font-size: ${theme.TabsFontsize};
background-color: transparent;
flex: 1;
padding: 1rem;
outline: 0;
&:hover {
background-color: ${theme.TabActiveBackground};
color: ${theme.TabActiveColour};
}
${({ active }) => active && `
background-color: ${theme.TabActiveBackground}
color: ${theme.TabActiveColour};
`}
`}
`;
const Item: FC<IButtonProps> = ({
children,
active,
setActivity,
}) => (
<Button
active={active}
onClick={() => setActivity}
>
{children}
</Button>
);
SetActivity是我传递给组件以引用的挂钩。
答案 0 :(得分:1)
onClick
方法返回的函数setActivity: Function
不应返回。应该是它的执行
onClick={() => setActivity()}
或者如果setActivity
函数已经自绑定,则可以立即将其传递给onClick
道具
onClick={setActivity}
IButtonProps
也具有setActivity
作为属性。这意味着您必须将其传递给Button
组件
const Item = (props: any) => {
const { children, active, setActivity, } = props;
return (
<Button
active={active}
setActivity={() => {}}
onClick={() => setActivity()}
>
{children}
</Button>
);
};