英文:
How to apply parent styled jsx to children?
问题
如何将父级样式的JSX应用到子组件?我的JSX样式被应用到下面的父级按钮元素(因为它有自己的JSX类),但没有应用到它的子元素。
这是父级按钮元素的代码:
export function LoginButton({children, className, ...props}){
return (
<>
<style jsx>
{`
.loginButton {
padding: .75rem 2rem;
width: 100%;
border-radius: 2rem;
background: var(--primary);
color: var(--back);
font-size: 2rem !important;
}
.loginButton:hover i {
transform: translateX(.5rem);
}
`}
</style>
<button className={`loginButton ${className}`} {...props}>
{children}
</button>
</>
)
}
这是我如何使用这段代码的示例:
<LoginButton className="flex center gap1">
<h3>Sign in</h3>
<i className="bx bxs-right-arrow-alt"></i>
</LoginButton>
<i>
元素没有获取按钮的JSX样式。我尝试过克隆元素并将JSX更新为全局,但都没有起作用。
如何将JSX样式应用于组件的子元素?
英文:
How can I apply parent styled JSX to child components? My JSX styles are being applied to the parent button element below (as it has its own JSX class), but not to its children.
Here's the code for the parent button element:
export function LoginButton({children, className, ...props}){
return (
<>
<style jsx>
{`
.loginButton {
padding: .75rem 2rem;
width: 100%;
border-radius: 2rem;
background: var(--primary);
color: var(--back);
font-size: 2rem !important;
}
.loginButton:hover i {
transform: translateX(.5rem);
}
`}
</style>
<button className={`loginButton ${className}`} {...props}>
{children}
</button>
</>
)
}
Here's an example of how I'm using this code:
<LoginButton className="flex center gap1">
<h3>Sign in</h3>
<i className="bx bxs-right-arrow-alt"></i>
</LoginButton>
The <i>
element is not getting the JSX styles for the button. I've tried cloning the elements and updating JSX to global but neither worked.
How can I apply the JSX styles to the component's children?
答案1
得分: 0
From this nextjs blog post
> 使用<style jsx>向组件添加的样式仅影响该组件内的元素,而不影响子组件。
在您的示例中,.loginButton
样式正常工作,但是.loginButton:hover i
不会应用,因为您的组件代码中没有 i
元素:
<button className={`loginButton ${className}`} {...props}>
{children}
</button>
> 有时,我们可能需要覆盖子组件的某个样式。为此,Styled JSX 提供了 :global(),以便访问一次性全局选择器。
您可以使用 :global(i)
来样式化子元素:
.loginButton:hover :global(i) {
transform: translateX(.5rem);
}
英文:
From this nextjs blog post
> The styles that we add to a component using <style jsx> affect only the elements inside that component, but not child components.
In your example, .loginButton
styles works correctly, however .loginButton:hover i
won't be applied because there is no i
element in your component code :
<button className={`loginButton ${className}`} {...props}>
{children}
</button>
> At times, we may need to override a certain style of a child component. To do this, Styled JSX provides :global(), giving access to one-off global selectors.
You can use :global(i)
to style the children elements :
.loginButton:hover :global(i) {
transform: translateX(.5rem);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论