![](/img/trans.png)
[英]use styled-components to share styles between components/elements
[英]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 沒有語法高亮它:
您在這里有幾個選擇:
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.