在簡單的 HTML 結構中,我可以實作如下。我想知道如何使用 React 和 Styled Component 做同樣的事情。
HTML
<div className="slider">
<section>Content A</section>
<section>Content B</section>
</div>
我可以像這樣定位該部分的樣式。
.slider section {
//some styling
};
如何在 React with Styled Component 中實作相同的效果。在這種情況下,我的滑塊 div 是一個樣式組件,該部分是一個 React 組件,如下所示。
<Slider>
<SectionComponent text="Content A />
<SectionComponent text="Content B" />
</Slider>
這是我嘗試過的,在 Slider CSS 代碼塊中,我嘗試對 SectionComponent 進行樣式設定,但不起作用。
樣式化組件 CSS
export const Slider = styled.div`
//some css styling
Slider SectionComponent {
//styling of the SectionComponent
}
`;
uj5u.com熱心網友回復:
一般來說,在使用 React 和 Styled Components 時,您不必組件化每個元素。通常,您只想這樣做以利用它們帶來的額外功能。
在您的情況下,這將是:
<Slider>
<section>Content A</section>
<section>Content B</section>
</Slider>
因此,您可以使用樣式組件來設定您的部分的樣式,例如:
const Slider = styled.div`
section {
//styling of the section
}
`;
如果您確實希望將部分也作為組件,那么您仍然應該能夠執行上述操作;我在下面的示例中添加了多種形式的部分。section作為 HTML 元素,StyledSection作為樣式組件,SectionComponent是一個回傳<section>.
簡單的作業示例:https : //codesandbox.io/s/react-fiddle-forked-5xt6p?file=/src/App.js
在樣式化組件中使用 CSS 時,假設您仍在使用普通的 CSS 檔案和 HTML 元素。如果您SectionComponent是 的孩子Slider并且是<section>. 然后,您可以按照與 CSS 相同的方式相應地選擇它。
uj5u.com熱心網友回復:
嘗試使用字串模板:
export const Slider = styled.div`
//some css styling
${SectionComponent} {
//styling of the SectionComponent
}
`;
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366115.html
標籤:javascript html css 反应 样式组件
