const NavBar = () => {
const [active, setActive] = useState<string>("tasks");
return {
<Container>
<MenuLink onClick=(() => setActive("settings")/>
<MenuLink onClick=(() => setActive("tasks")/>
<MenuLink onClick=(() => setActive("wallets")/>
</Container>
}
選單鏈接.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;
}
`;
setActive每當單擊 MenuLink 項時,我都想觸發。但是,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在自定義組件中使用(和其他標準“道具”)。
uj5u.com熱心網友回復:
您可以將 NavBar 的界面更改為
interface MenuLinkProps {
$active: boolean;
to: string;
title: string;
[key : string] : any
}
接受任何靜止的道具這不會解決您的錯誤,請提供您在哪里以及如何使用 $active
uj5u.com熱心網友回復:
因此,您必須將父單擊方法作為道具傳遞給孩子
父組件:
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478618.html
上一篇:反應,在兄弟組件之間傳遞狀態
