Skip to main content

Basic 基礎知識

const Card = () => {
return <div>Card</div>;
};
export default card;
const Card = () => {
return React.createElement("div", { chidren: "Card" });
};
export default card;
{
card();
}
<Card></Card>
☝️ 小訣竅

熱鍵自動出現 import

export#

default 不用特別去指定 import 拿的是哪一個

沒有 default 的話須額外指定或使用解構

export default name;
import Name from "./Name";
import { Foo } from "./Bar";
import * as Card from "./Bar";
Card.foo;

props#

就如同我們自己定義的屬性

資料(xxx 部分)可用變數方式寫在屬性(attributes),再透過props物件的參數去存取所有變數,再透過解構,放在對應的 tag 內

//外面
<Card title="Card1" description="card1 desc">
//裡面
const Card=(props) =>{
const {title,description} = props;
}

children#

保留字

//外面
<Card title="Card1"> XXX </Card>;
//裡面
const Card = (props) => {
const { title, children } = props;
};
<div>{children}</div>;

map#

利用陣列儲存資料,再利用.map()方法將資料放進 html 裡 ,並利用 id,讓 react 方便辨別每筆資料

style#

react inline style 無法直接解析 css 字串,是利用 CSS in JS 方式,也就是把 css 包成 JS 的物件

render html string#

當傳入參數的內容要放 HTML 時,可以小心使用 dangerouslySetInnerHTML(但有資安疑慮)

<Card title="Card1"> XXX </Card>;
//裡面
const Card = (props) => {
const { discription, children } = props;
};
<div dangerouslySetInnerHTML={{ __html: "<a>hi</a>" }}>{children}</div>;
<div dangerouslySetInnerHTML={{ __html: discription }}>{children}</div>;

SVG#

import { ReactComponent as AsosLogo} from "../../images/dog.png";
//底層有svgr的library會把svg轉成Component
...
return
...
<AsosLogo className="logo" fill="red" />
//可自己加class //可改顏色

CSS Module 封裝 CSS#

css 直接放 src,沒封裝的話...

  • 編譯不到圖片路徑
  • css 檔會跑到全域 ,在編譯後會被放在 global(最外層),造成渲染錯誤。

作法

  • 改 css 檔名稱(加.module)
  • 底層實做方法:把 className 變成複合名字, ex: className=__src_Home_Component

Styled Component#

  • Use case 1: 產生新的 styled-component
import styled from "styled-component"
// 無中生有 (產生新標籤<div>, 可替換標籤)
const StyledDiv = styled.div`
color: red;
`
// inline-style syntax
<div style= {{ color: "red" }}>This is red.</div>
// style-component syntax
<StyledDiv> This is red.</StyledDiv>
  • Use case 2: 在現有的 component 加上 style
import styled from "styled-component"
// 在現有的標籤<Component>加style
const StyledComponent = styled(Component)`
color: red'
`
<StyledComponent />

若 style 太多,可以開新檔案 "{NAME}.styled.js"並且放入 styled component,並在 styled component 前面加上 export const

切出來的好處:

  • style 太多看起來比較不會亂
  • 若有共用樣式則可以重複利用

i mport 方法:

import { StyledComponent1, StyledComponent2 } from "./{NAME}.styled.js"
...
<StyledComponent1 />
<StyledComponent2 />

styled component 中使用 props

StyledComponent1 = styled(Component1) `
// fetch the variable passed into the styled component
fill : ${props => props.varient};
:hover {
fill: ${props => props.hoverColor};
}
`
<StyledComponent1 varient="purple" hoverColor="red" />
StyledComponent1 = styled(Component1) `
// fetch the variable passed into the styled component and add condition
fill : ${ (props) => (props.varient === "primary"
? "green" : "purple") };
`
// a green component
<StyledComponent1 varient="primary" />
// a purple component
<StyledComponent1 />

參考的學習資料和引用