Reactjs中的样式组件

时间:2018-06-11 10:35:12

标签: javascript css reactjs styled-components

如何在app.js中将我的css代码应用为样式组件? 如何将这个“.container> div”转换为样式组件并在我的app.js中使用它。通过npm install安装样式组件然后导入它。我被困在这里。我无法在样式组件中应用某些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;
 }

1 个答案:

答案 0 :(得分:1)

基于div创建一个用作容器的组件,并写下CSS。这里的技巧是将适当的样式应用于组件div的子项Container,您需要在模板文字内部使用&(代表父选择器)来创建所需的嵌套因此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;