【问题标题】:Extending styled components扩展样式组件
【发布时间】:2019-03-01 17:31:38
【问题描述】:

我有一个Field Formik 的组件,为了应用我做的自定义 CSS:

const Input = styled(Field)`
  // CSS goes here
`

并使用Input 组件,工作正常。但是我在很多地方都使用完全相同的 CSS,所以我将这些 CSS 提取到名为SuperInput的独立样式组件@

现在,如何扩展样式组件?我需要类似的东西

const Input = styled(Field)`
  // inlucde CSS from SuperInput component here
`

示例代码。

import styled from 'styled-components'

const SuperInput = styled.input`
  // CSS here
`
import { Field } from 'formik'
import { SuperInput } from 'styled_components/super_input'

const SomeFormComponent = () => (
  <>
   // How to use here <Field /> that has <SuperInput /> CSS applied?
  </>
)

【问题讨论】:

    标签: styled-components formik


    【解决方案1】:

    基本上,您只需要在模板文字内扩展或附加即可使其工作。您可以保留常见的 CSS,例如

    import styled, { css } from "styled-components"
    
    const commonCss = css`
      background: red;
    `
    

    并且可以像这样在你的组件中使用它:

    const Input = styled(Field)`
    // CSS goes here
      ${commonCss}
      color: hotpink;
    `;
    
    const Input1 = styled(Field)`
      ${commonCss}
      color: lightblue;
    `;
    

    这应该允许您在各种样式的组件中使用通用 CSS。 更多信息,您可以阅读css styled component API

    编辑: 样式化的组件创建 HOC。 添加 superInput 定义后,我了解您要执行的操作。因此,您的 superInput 正在创建一个具有您尝试重用的某些 css 属性的按钮。在这种情况下,当您使用 Field 并尝试扩展作为按钮的 SuperInput 时,这是没有意义的。你的 Field 组件默认是一个输入元素(文本框),它可以是复选框,单选,文件输入也可以。任何用 superInput 编写的 CSS 都可以按照我上面提到的方式提取并在多个地方使用。您尝试做的方式不是样式化组件的设计方式。这是我的理解

    注意:关于这是否可能,我在这里可能是错误的。但根据我的意识,这就是我能说的。如果我错了,请随时纠正我。

    【讨论】:

    • 是的,我知道,但是 commonCss(在我的例子中是 SuperInput)不是独立的 styled-component 组件,不能作为一个组件使用。
    • 当我们说 SuperInput 不是一个独立的样式组件时,我们的意思是什么。你能告诉我 SupeIinput 的定义吗?
    • 感谢您添加的示例。您在这里展示了示例用法,但我要问的是 styled_components/super_input 文件中 SuperInput 的定义。看到这只能让我明白问题所在!!
    • 哦,知道了。已添加。
    猜你喜欢
    • 2019-03-28
    • 2020-01-09
    • 1970-01-01
    • 2020-06-12
    • 2020-12-27
    • 2018-10-05
    • 2019-06-04
    • 2020-08-20
    • 2020-04-01
    相关资源
    最近更新 更多