【问题标题】:Share the same styles between two types of component with React Styled Components使用 React Styled Components 在两种类型的组件之间共享相同的样式
【发布时间】:2019-02-09 07:19:03
【问题描述】:

我想将完全相同的样式应用于样式化的input 元素和样式化的select 元素。

目前,我正在使用字符串插值来执行此操作:

const styles = `
    background-color: white;
    width: 100%;
    border: 0 solid transparent;
    border-radius: 10px;
    margin-bottom: 20px;
    padding-top: 5px;
    padding-bottom: 5px;
    font-size: 1.2rem;
`

const Select = styled.select`${styles}`
const Input = styled.input`${styles}`

有没有更好的不涉及使用“原始”字符串的方法?使用原始 styles 字符串的缺点是 Visual Studio Code 没有语法高亮它:

【问题讨论】:

    标签: css reactjs typescript visual-studio-code styled-components


    【解决方案1】:

    你有几个选择:

    css helper function:

    const styles = css`
      background-color: white;
      // ...
    `;
    
    const Select = styled.select`${styles}`;
    const Input = styled.input`${styles}`;
    

    "as" polymorphic prop(在v4中添加):

    <Select as="input">
      ...
    </Select>
    

    withComponent method(弃用候选):

    const Select = styled.select`
      background-color: white;
      // ...
    `;
    const Input = Select.withComponent('input');
    

    【讨论】:

      【解决方案2】:

      您可以使用css 标记的模板文字:

      import styled, { css } from "styled-components";
      
      const styles = css`
        background-color: white;
        width: 100%;
      `;
      
      const Select = styled.select`${styles}`;
      const Input = styled.input`${styles}`;
      

      这应该会正确突出显示语法(尚未测试)。

      【讨论】:

        猜你喜欢
        • 2020-09-21
        • 2021-08-26
        • 2017-07-27
        • 1970-01-01
        • 2018-08-21
        • 2021-11-04
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        相关资源
        最近更新 更多