01、Create React App
$ create-react-app YOUR_APP_NAME
Create React App 是一個用于創建 React 項目的 CLI。
02、JSX
const element = <h1>Hello, world!</h1>;
我們可以通過 JSX 在 JavaScript 中編寫 HTML。
03、在 JSX 中嵌入表達式
const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;
只需使用 {} 來包裝 JavaScript 表達式。
04、創建一個組件
import React from 'react'
const Hello = () => <div>Hello World</div>
export default Hello
它是一個簡單的、無狀態的、功能性的組件。
05、創建類組件
import React from 'react'
class Hello extends React.Component {
render() {
return <div>Hello World</div>
}
}
export default Hello
06、將值傳遞給組件
const User = ({name, email}) => {
<div>
<div> name: {name} </div>
<div> email: {email} </div>
</div>
}
export default User
用法:
<User name="Jon" age="35">
07、組件嵌套
const Child = (props) => (
<div>{props.message}</div>
)
const Father = () => (
return (<div>
<div> I am father</div>
<Child message="aaa"></Child>
</div>)
)
08、向組件添加狀態
import { useState } from "react";
export default function Counter(){
// Declare a new state variable, which we'll call "count"
let [count, setCount] = useState(0)
return <div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> add</button>
</div>
}
09、聲明多個狀態變量
當然,我們可以使用 useStates 定義多個狀態。
function ManyStates() {
// Declare multiple state variables!
const [name, setName] = useState('');
const [age, setAge] = useState(0);
const [todos, setTodos] = useState([{ text: 'Eat' }]);
// ...
}
10、使用效果
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
11、處理事件
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('You clicked submit.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
12、條件渲染
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
用法:
<Greeting isLoggedIn={false} />
13、列表組件
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<li>{number}</li>
);
return (
<ul>{listItems}</ul>
);
}
用法:
<NumberList numbers={[1, 2, 3, 4, 5]} />)