簡體   English   中英

使用 React Styled Components 在兩種類型的組件之間共享相同的樣式

[英]Share the same styles between two types of component with React Styled Components

我想將完全相同的樣式應用於樣式化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 輔助函數

const styles = css`
  background-color: white;
  // ...
`;

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

“作為”多態道具(在v4 中添加):

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

withComponent 方法(棄用的候選者):

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

您可以使用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}`;

這應該得到正確的語法突出顯示(尚未測試)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM