[英]how do you share styles in react?
我有一個組件:
const Title = styled(Typography)({
fontFamily: 'Manrope',
fontStyle: 'normal',
fontWeight: 600,
fontSize: 28,
lineHeight: '38px',
color: '#20232C',
marginTop: 17,
height: 50,
display: 'block',
});
在這個組件中我像這樣使用它..
<Title>Title here</Title>
可以想象,Title 是可以在應用程序的許多地方使用的東西。 所以我把上面的Title
放在components/Titles/styles.tsx
中。 然后從那里導出。
現在,無論我在哪里需要它,我都會導入Title
並使用它。
問題:在其他一些地方,這個 Title 需要有不同的fontWeight
和marginTop
等等。 誰知道,將來,也許在一個地方,它可能需要與當前Title
styles 不同的 4-5 個字段。
我們如何解決這個問題?
方式一:
export const Title = styled(Typography)(
({ fontWeight }: { fontWeight?: number }) => ({
width: 'fit-content',
fontFamily: 'Manrope',
fontStyle: 'normal',
fontWeight: fontWeight || 'normal',
fontSize: 28,
lineHeight: '25px',
color: '#20232C',
marginTop: '17px',
}),
);
由於我將fontWeight
可選,我們可以對所有字段執行此操作。
您如何看待這種方式以及如何處理此類情況? 這幾乎是我第一次在js中處理styles。 我來自vue.js
世界。
將 fontWeight 作為屬性當然很好,但在進一步擴展時可能會變得過於復雜。
另一個選項是將 Title 繼承到另一個樣式組件中(當您找到有意義的命名用例時總是最好的),例如:
export const Subtitle = styled(Title)`
font-size: 24px;
font-weight: bold;
`
這是特定於樣式組件的。
有兩種常用方法,均在文檔中介紹。
const Button = styled.button` /* Adapt the colors based on primary prop */ background: ${props => props.primary? "palevioletred": "white"}; color: ${props => props.primary? "white": "palevioletred"}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; render( <div> <Button>Normal</Button> <Button primary>Primary</Button> </div> );
// The Button from the last section without the interpolations const Button = styled.button` color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; // A new component based on Button, but with some override styles const TomatoButton = styled(Button)` color: tomato; border-color: tomato; `; render( <div> <Button>Normal Button</Button> <TomatoButton>Tomato Button</TomatoButton> </div> );
您應該能夠在 Title 標簽中使用道具並將它們傳遞給單個組件,如下所示:
<Title thisTitlesHight="80px" thisTitlesWidth="50px">Title Here<Title>
然后在您的子組件中使用這些道具:
export const Title = styled(Typography)(
({ fontWeight }: { fontWeight?: number }) => ({
height: this.props.thisTitlesHeight,
width: this.props.thistitlesWidth
}),
);
您還必須在 function 中定義道具。
我創建了一個 codeSandbox,因此您可以看到它的代碼: https://codesandbox.io/s/stupefied-wildflower-wmw26?file=/src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.