【问题标题】:Styled components in ReactjsReactjs 中的样式化组件
【发布时间】:2018-11-20 14:05:23
【问题描述】:

如何将我的 css 代码应用为 app.js 中的样式组件? 如何将此“.container > div”转换为样式组件并在我的 app.js 中使用它。通过 npm install 安装 styled-component 然后导入它。我被困在这里。我无法在样式组件中应用某些 CSS 样式。

App.js

 import React, { Component } from 'react';
 import './App.css';

 class App extends Component{
  render(){
    return (

      <div class="container">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      </div>
           );
         }
       }

 export default App;

App.css

.container
 {
   display: grid;
   grid-template-columns: auto auto auto;
   grid-template-rows: 50px 50px;
 }

.container > div 
 {
   display: flex;
   justify-content: center;
   align-items: center;
   font-size: 2em;
   color: #ffeead;
 }

html, body 
 {
 background-color: #ffeead;
 margin: 10px;
 }

.container > div:nth-child(1n)
 {
  background-color: #96ceb4;    
 }

.container > div:nth-child(3n) 
 {
  background-color: #88d8b0;
 }

.container > div:nth-child(2n)
 {
   background-color: #ff6f69;
 }

.container > div:nth-child(4n)
 {
   background-color: #ffcc5c;
 }

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    创建一个基于div 的组件作为容器并写下你的CSS。这里的技巧是对组件Container 的子div 应用适当的样式,您需要在模板文字内使用&amp;(代表父选择器)来创建所需的嵌套,以便SC 可以生成适当的CSS 类。

    import React, { Component } from 'react';
    import styled from 'styled-components';
    import './App.css';
    
    const Container = styled.div`
      display: grid;
      grid-template-columns: auto auto auto;
      grid-template-rows: 50px 50px;
    
      & > div {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 2em;
        color: #ffeead;
      }
    
      & > div:nth-child(1n) {
        background-color: #96ceb4;    
      }
    
      & > div:nth-child(3n) {
        background-color: #88d8b0;
      }
    
      & > div:nth-child(2n) {
        background-color: #ff6f69;
      }
    
      & > div:nth-child(4n) {
        background-color: #ffcc5c;
      }
    `;
    
    
    class App extends Component{
      render(){
        return (
          <Container>
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
            <div>5</div>
            <div>6</div>
          </Container>
        );
      }
    }
    
    export default App;
    

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 2021-04-03
      • 2019-01-07
      • 2021-07-04
      • 2017-08-25
      • 2020-10-27
      • 2020-02-13
      • 2020-07-19
      • 2021-07-05
      相关资源
      最近更新 更多