const NavBar = () => {
const [active, setActive] = useState<string>("tasks");
return {
<Container>
<MenuLink onClick=(() => setActive("settings")/>
<MenuLink onClick=(() => setActive("tasks")/>
<MenuLink onClick=(() => setActive("wallets")/>
</Container>
}
MenuLink.tsx:
interface MenuLinkProps {
$active: boolean;
to: string;
title: string;
}
function MenuLink({ $active, to, title, ...rest }: MenuLinkProps) {
return (
<Container $active={$active} to={to} {...rest}>
{title}
</Container>
);
}
interface ContainerProps {
$active: boolean;
to: string;
}
const Container = styled(Link)<ContainerProps>`
width: 70px;
height: 35px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 3px;
font-style: normal;
font-weight: 500;
font-size: 14px;
line-height: 17px;
letter-spacing: 0.025em;
text-decoration: none;
color: ${({ $active }: ContainerProps) => ($active ? "#4C6C94" : "#908E87")};
background: ${({ $active }: ContainerProps) => ($active ? "#1D232B;" : "#100F0D")};
&:not(:first-child) {
margin-left: 24px;
}
`;
我想在单击MenuLink项时触发setActive
。然而,TypeScript抱怨我没有onClick
作为MenuLinkProps
的属性。我不确定这是否正确,因为当我把onClick
作为属性时,我得到这个错误:
Cannot update a component (`NavBar`) while rendering a different component (`MenuLink`). To locate the bad setState() call inside `MenuLink`, follow the stack trace as described in
我不太确定我应该如何在自定义组件中使用onClick
(和其他标准"prop ")。
你可以改变你的导航栏界面为
interface MenuLinkProps {
$active: boolean;
to: string;
title: string;
[key : string] : any
}
接受任何静止的道具这不会修复您的错误,请提供您在哪里以及如何使用$active
所以,你必须将父类click方法作为props传递给子类
父组件:
const NavBar = () => {
const [active, setActive] = useState<string>("tasks");
var menuOnClick: (action:string) => {setActive(action)};
return {
<div>
<Container>
<MenuLink onClick=(this.menuOnClick} />
<MenuLink onClick=(this.menuOnClick} />
<MenuLink onClick=(this.menuOnClick} />
</Container>
</div>
}
}
子组件:
<Container $active={$active} to={to} {...rest} onClick ={() => this.props.onClick(title)} >
{title}
</Container>