我正在使用樣式化組件并具有以下代碼
TopNav.tsx
import {
Container,
SearchContainer,
SearchBox,
NotificationsContainer,
NotificationsDetails,
NotificationsSummary,
NotificationsCounter,
NotificationsItems,
NotificationsHeader,
NotificationsMarkReadText,
Notification,
NotificationTopper,
NotificationContent,
NotificationUnread,
NotificationUnreadDot,
NotificationsShowAll
} from '@/components/Layout/TopNav.style';
import Link from 'next/link';
import { MagnifyingGlassIcon, BellIcon } from '@heroicons/react/24/outline';
import { NOTIFICATIONS } from '@/constants/Notifications';
import { ThemeSwitch } from '@/components/ThemeSwitch/ThemeSwitch';
interface TopNavProps {
fullWidth: Boolean;
}
export const TopNav = ({ fullWidth }: TopNavProps) => {
return (
<Container>
<SearchContainer>
<SearchBox>
<form>
<button type="submit">
<MagnifyingGlassIcon />
</button>
<input type="text" placeholder="The everything search..." />
</form>
</SearchBox>
</SearchContainer>
<NotificationsContainer>
<NotificationsDetails>
<NotificationsSummary>
<BellIcon />
<NotificationsCounter>10</NotificationsCounter>
</NotificationsSummary>
<NotificationsItems>
<NotificationsHeader>
<NotificationsMarkReadText>
Mark all as read
</NotificationsMarkReadText>
<NotificationsShowAll>
<Link href="/notifications">Show all</Link>
</NotificationsShowAll>
</NotificationsHeader>
{NOTIFICATIONS.map(({ date, message, url }, index) => {
return (
<Notification key={`notify_${index}`}>
<NotificationContent>
<Link href={url} target="_blank">
<NotificationTopper>
<strong>{date}</strong>
<NotificationUnread>
<NotificationUnreadDot />
</NotificationUnread>
</NotificationTopper>
<p>{message}</p>
</Link>
</NotificationContent>
</Notification>
);
})}
</NotificationsItems>
</NotificationsDetails>
</NotificationsContainer>
<ThemeSwitch />
</Container>
);
};
TopNav.style.ts
import styled from 'styled-components';
import mq from '@/styles/mq';
export const Container = styled.nav`
border-bottom: var(--border2px) solid var(--gray500);
background-color: var(--gray100);
width: ${(props) => props.fullWidth}? '100%' : calc(100% - 5rem);
padding: 1.06rem 0.5rem;
align-items: center;
position: fixed;
display: flex;
z-index: 999;
gap: 2rem;
right: 0;
top: 0;
@media screen and ${mq.minMedium} {
width: calc(100% - 15rem);
padding: 1.25rem 0.5rem;
}
`;
export const SearchContainer = styled.div`
flex: 12;
`;
...
由于我的樣式位于一個單獨的檔案中以保持代碼整潔,我該如何將其傳遞fullWidth到我的樣式檔案中?所以我可以動態設定導航的寬度。
我查看了檔案,似乎所有示例都將所有代碼放在同一個檔案中。
uj5u.com熱心網友回復:
如何將 fullWidth 傳遞到我的樣式檔案中?所以我可以動態設定導航的寬度。
如果我沒有理解錯的話,您需要將 傳遞fullWidth給Container組件。
<Container fullWidth={fullWidth}>
但是,您的樣式檔案中也存在語法錯誤,因為
width: ${(props) => props.fullWidth}? '100%' : calc(100% - 5rem);
顯然會失敗,因為三元運算子在字串文字之外。只需將其更改為:
width: ${({ fullWidth }: { fullWidth: boolean }) => fullWidth ? '100%' : 'calc(100% - 5rem)'};
uj5u.com熱心網友回復:
您創建的樣式化組件是引擎蓋下的 React 組件,因此傳遞 props 就像將 props 傳遞給 React 組件一樣。
這是演示:
<Container fullWidth={yourValue} />
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/533635.html
