简体   繁体   English

样式组件 - 创建类方法?

[英]styled-components - create class method?

I need a way to create classes without styled nor css method.我需要一种方法来创建没有styledcss方法的类。

Lets assume proper style system with components having only basic styles, but not positioning, margin etc.让我们假设适当的样式系统,组件只有基本样式,但没有定位、边距等。

eg例如

const Root = styled.div`/* Some styles */`

export const MyComponent = ({className}) => <Root className={className} />

So this is easy, I attach private styles for component and I allow it to receive and apply class from parent.所以这很容易,我为组件附加了私有样式,并允许它从父级接收和应用类。

If I have "classic" css, I would use it like this如果我有“经典”的 css,我会像这样使用它

import styles from 'some-styles.module.css';

...

<MyComponent className={styles.someStyle} />

Which will work as expected.这将按预期工作。

Here is the problem:这是问题所在:

How do I create a class with styled-components only?如何创建仅包含styled-components的类? It was working with Glamorous once, but SC (and Emotion) is not returning class name from css .它曾经与Glamorous一起工作,但 SC(和 Emotion)没有css返回类名。

I can't use separate css files just to allow this styling, which should be common use case (parent setting size of children)我不能使用单独的 css 文件来允许这种样式,这应该是常见用例(子项的父级设置大小)

Edit & solution in Emotion在情感中编辑和解决方案

I figured out that Emotion adds extra property css which is available for every jsx element.我发现 Emotion 添加了额外的属性css ,可用于每个 jsx 元素。 It can be used to native <div> , styled <Div> or custom React component <MyComponent .它可以用于原生<div> 、样式化<Div>或自定义 React 组件<MyComponent Babel is changing css attribute with css({...}) to className during compilation. Babel 在编译期间将css({...}) css属性更改为 className。 If <MyComponent> only accepts prop className it will receive it from parent via css prop.如果<MyComponent>只接受 prop className ,它将通过css prop 从父级接收它。

I still belive I should be able to somehow pass styles from parent to child.我仍然相信我应该能够以某种方式将样式从父级传递给子级。

There is a way to do that, but no exactly the way you want to do.有一种方法可以做到这一点,但并不完全是您想要的方式。

In react js (you can't do this in React Native yet), you can pass the child component inside the parent style and it will add the style in the child when it's wrapped by the parent.在 React js 中(你还不能在 React Native 中这样做),你可以在父样式中传递子组件,当它被父样式包裹时,它会在子组件中添加样式。

eg例如

const ParentComponent = styled.div`
    ${ChildComponent} {
         /* Child css*/
    }
`

Sorry if formatting is bad, I'm on mobile对不起,如果格式不好,我在手机上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM