css 导入导出样式组件React

icomxhvb  于 2022-12-24  发布在  React
关注(0)|答案(4)|浏览(213)

我想在样式和应用程序之间拆分页面
范例
页面样式. 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?

m3eecexj

m3eecexj1#

另一个选项,你可以这样导出:

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>
 );
}
stszievb

stszievb2#

有一种很好的方法可以做到这一点,这种方法还可以让你知道哪个组件是样式化的组件还是单个组件。

// 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>
 );
}
gwo2fgha

gwo2fgha3#

Dae Hyeon Mun's approach非常棒,但是您可以使用通配符导入来进一步简化它,从而避免重构styles.js文件,这实际上创建了一个模块对象,因此您不必这样做!:

// 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>
 );
}

More details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#creating_a_module_object

ocebsuys

ocebsuys4#

你可以使用"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>

相关问题