In this lesson, we remove the mapping between a React component and the styles applied to it via classnames. We write our styles directly within the component, in a real CSS syntax, with the full power of JavaScript.
Old:
import React, { Component } from "react";
import "./App.css";
/* ======================= */
/* ===== sample data ===== */
/* ======================= */
const people = [
{ name: "Anna", sex: "female", age: 28 },
{ name: "John", sex: "male", age: 31 },
{ name: "Tim", sex: "male", age: 7 },
{ name: "Bella", sex: "female", age: 4 }
];
/* ============================== */
/* ===== the main component ===== */
/* ============================== */
const App = () =>
;
/* =========================== */
/* ===== the Person card ===== */
/* =========================== */
const Person = props =>
This {props.sex} is currently{" "} {props.age} years old.
;
export default App;
.person {
padding: 1.75rem;
margin: .5rem;
border-radius: 4px;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);
color: white;
}
.person--male {
background: #44bccc;
}
.person--female {
background: #f973bc;
}
.person__name {
margin-top:;
font-weight:;
margin-bottom: .75rem;
}
.person__description {
margin:;
line-height: 1.5;
}
.person__description strong {
font-weight:;
}
body {
margin:;
font-family: -apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Helvetica,
Arial,
sans-serif,
"Apple Color Emoji",
"Segoe UI Emoji",
"Segoe UI Symbol";
}
Convert to styled-complement:
import React, { Component } from "react";
import styled from "styled-components";
import "./App.css";
/* ======================= */
/* ===== sample data ===== */
/* ======================= */
const people = [
{ name: "Anna", sex: "female", age: 28 },
{ name: "John", sex: "male", age: 31 },
{ name: "Tim", sex: "male", age: 7 },
{ name: "Bella", sex: "female", age: 4 }
];
/* ============================== */
/* ===== the main component ===== */
/* ============================== */
const App = () =>
;
const Name = styled.h2`
margin-top: 0;
font-weight: 900;
margin-bottom: .75rem;
`;
const Bio = styled.p`
margin: 0;
line-height: 1.5;
strong {
font-weight: 900;
}
`;
const Card = styled.div`
padding: 1.75rem;
margin: .5rem;
border-radius: 4px;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.1);
color: white;
background: ${props => (props.sex === "male" ? "#44bccc" : "#f973bc")}
`;
/* =========================== */
/* ===== the Person card ===== */
/* =========================== */
const Person = props =>
export default App;
body {
margin:;
font-family: -apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Helvetica,
Arial,
sans-serif,
"Apple Color Emoji",
"Segoe UI Emoji",
"Segoe UI Symbol";
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章