[英]import export styled component reactjs
我想在樣式和應用程序之間拆分頁面
例子
在頁面 style.js
import styled from "styled-components";
//i dont know how to export all const
export const Container = styled.div`
display: flex;
flex-direction: row;
`;
export const Sidebar = styled.div`
width: 20%;
height: 100%;
background-color: #f9f9f9;
`;
並在頁面 app.js
import * as All from "./style.js"
//i dont know, how to import all const in style.js
function App(){
return(
<Container>
<Sidebar>
</Sidebar>
</Container>
)}
style.js中的const那么多,如何導出和導入所有的const?
您可以像這樣導出另一個選項:
import styled from "styled-components";
const Container = styled.div`
display: flex;
flex-direction: row;
`;
const Sidebar = styled.div`
width: 20%;
height: 100%;
background-color: #f9f9f9;
`;
export {Container,Sidebar}
你可以像這樣導入:
import { Container,Sidebar } from './style';
function App() {
return (
<Container>
<Sidebar>
</Sidebar>
</Container>
);
}
有一種很好的方法可以做到這一點。 這種方式還可以讓您知道哪個組件是樣式化組件或單個組件。
// style.js
export const Styled = {
Container: styled.div`
display: flex;
flex-direction: row;
`,
Sidebar: styled.div`
width: 20%;
height: 100%;
background-color: #f9f9f9;
`,
}
import { Styled } from './style';
function App() {
return (
<Styled.Container>
<Styled.Sidebar>
</Styled.Sidebar>
</Styled.Container>
);
}
Dae Hyeon Mun 的方法很棒,但是您可以進一步簡化它,避免使用通配符 import重構您的styles.js
文件,這實際上創建了一個模塊 object,因此您不必:
// style.js
export const Container = styled.div`
...
`;
export const Sidebar = styled.div`
...
`;
// app.js
import * as Styled from './style';
function App() {
return (
<Styled.Container>
<Styled.Sidebar>
</Styled.Sidebar>
</Styled.Container>
);
}
更多細節: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#creating_a_module_object
您可以像導出時一樣使用“export const”。 導入這些常量的最簡單方法是:
import * as styled from "./style.js" //this will import all 'export const' containing 'styled' from "./style.js" function App(){ return( <Container> <Sidebar> </Sidebar> </Container> )}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.