【问题标题】:How to make a layout with Styled Components?如何使用样式化组件进行布局?
【发布时间】:2019-08-22 23:19:21
【问题描述】:

由于 React 的目的是使组件可重用,并且页面的布局可以从一个应用程序到另一个应用程序发生巨大变化,我不确定将我的布局特定样式放在哪里。有什么建议吗?

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    组件的放置应由组件的“消费者”决定。因此,例如,如果您有 3 个组件:

    • ComponentA
      • ComponentB
        • ComponentC

    • ComponentC 将决定其所有子组件的位置。
    • ComponentB 将决定其所有子组件的位置,其中 将包括ComponentC
    • ComponentA 将决定其所有子组件的位置,其中 将包括ComponentB

    【讨论】:

      【解决方案2】:

      如果你指的是 React 中的全局样式,你有两个选择:

      选项 1:将它们作为常规 CSS 文件放入 - 看看 Create-React-App 是如何做到的 - 或者只是将它们添加到您正在渲染应用程序的 index/html

      选项 2:样式化组件支持主题化,这意味着它们为您提供 <ThemeProvider /> 元素,然后您可以在下游的任何组件中使用提供的样式。这里是the docs including a basic example

      另一方面,如果您指的是布局但在组件/子组件级别上,您基本上将布局样式拉到尽可能高的位置。一个例子是有一个元素有自己的样式;像这样:

      // Layout.js
      const myStyledContainer = styled.div`
      display: flex;
      `
      export default (props) => <myStyledContainer>{props.children}</myStyledContainer>
      

      那么在你App.js 你会有类似的东西:

      return (
      <Layout>
      
      *... your other components or pages or whatever*
      </Layout>
      

      这是一个见仁见智的问题,所以只需尝试一下,看看什么对您的项目有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-20
        • 2021-11-01
        • 2014-12-06
        • 2020-09-26
        • 2020-09-22
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        相关资源
        最近更新 更多