我正在尝试构建响应式 header 组件。它应该使用 display:inline-block
显示所有导航链接。在桌面上时,它应该使用 display:block
显示所有导航链接在移动设备上时。
注意:我使用的是 react-responsive
做媒体查询,所以:
import Responsive from 'react-responsive';
function Mobile(props) {
return(<Responsive {...props} maxWidth={800}/>);
}
function Desktop(props) {
return(<Responsive {...props} minWidth={801}/>);
}
<Mobile>
将在移动设备上呈现,并且 <Desktop>
将呈现在桌面上。那部分工作正常。我只是无法相应地更改样式。
请注意,下面的所有代码都在 Header.js
中.
我目前的方法如下:
Header
组件
是我的其余代码导出和使用的那个。它呈现 <MobileHeader>
在手机上和<DesktopHeader>
在桌面上。两者都是样式组件。
function Header(props) {
return(
<React.Fragment>
<Mobile>
<MobileHeader
authUser={props.authUser}
/>
</Mobile>
<Desktop>
<DesktopHeader
authUser={props.authUser}
/>
</Desktop>
</React.Fragment>
);
}
HeaderBase
组件:
我的两个样式 <MobileHeader>
和 <DesktopHeader>
应该设置 HeaderBase
的样式组件,如下(简化):
function HeaderBase(props) {
return(
<header>
<div>
<h1>Header</h1>
<ul>
<li>
<Link to={ROUTES.HOME}>Home</Link>
</li>
<li>
<Link to={ROUTES.ACCOUNT}>Account</Link>
</li>
</ul>
</div>
</header>
);
}
问题:
MobileHeader
和 DesktopHeader
组件:
我想这就是问题所在。我可以像在 li
中那样在样式化的自定义组件中引用 html 标签吗? ?因为这似乎行不通。不过,这在我设计常规 html 标签的样式时有效。
你们推荐另一种方法吗?我的最终目标是拥有一个覆盖式侧边导航栏,当用户使用移动设备时,它会在您点击时从左侧出现。在桌面上我会有一个常规的 inline-block
导航栏。由于每种情况下的链接都是相同的,我想我应该重用 HeaderBase
并使用 styled-components 对其进行相应的设置。
const MobileHeader = styled(HeaderBase)`
li {
display: block;
}
`;
const DesktopHeader = styled(HeaderBase)`
li {
display: inline-block;
padding: 5px;
margin: 0;
box-sizing: border-box;
}
`;
最佳答案
刚发现哪里出了问题:
根据 styled-components
docs :
If you use the styled(MyComponent) notation and MyComponent does not render the passed-in className prop, then no styles will be applied. To avoid this issue, make sure your component attaches the passed-in className to a DOM node:
所以我需要一个由我的组件呈现的“父”html 节点来接收带有样式组件样式的 className Prop :
function HeaderBase(props) {
return(
<header>
<div className={props.className}> // <----- NOW IT WORKS!
<h1>Header</h1>
<Mobile>☰ I am mobile header</Mobile>
<ul>
<li>
<Link to={ROUTES.HOME}>Home</Link>
</li>
关于javascript - 如何使用 styled-components 为我自己的组件(响应式标题)设置样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54541159/