React Cheat Sheet
Tạo ứng dụng React
// Create a new app
npx create-react-app my-app-name
// Run the created app
cd my-app-name
yarn start
// http://localhost:3000
Chức năng Component React đầu tiên
- Không cần import React from 'react' (kể từ React 17)
- Phải viết hoa chữ cái đầu tiên
- Phải return JSX
(src/App.js)
// React component
function App(){
return <h1>Hello World</h1>
}
export default App;
Làm thế nào component này được hiển thị cho trình duyệt? Tệp chính là src / index.js và trong tệp đó có hướng dẫn để kết xuất component.
ReactDOM.render(<App />, document.getElementById('root'))
Component App sau đó sẽ được hiển thị bên trong div public / index.html 'root'
Import Component
Component sẽ được tạo trong các tệp riêng biệt. Mỗi Component cần được export và sau đó import
function Greeting(){
return <h1>Hello World</h2>
}
export default Greeting
Component này sau đó có thể được import
import Greeting from './Gretting'
function App(){
return <Greeting />
}
hoặc name export...
export function Greeting(){
return <h1>Hello World</h2>
}
Component này sau đó có thể được import
import {Greeting} from './Gretting'
Quy ước đặt tên BEM
return (
<div className="app">
<h1 className="app_title">Welcome to my application: {appTitle}</h1>
<div className="product">
<h1 className="product__name--large">Product name: {product.name}</h1>
<h1 className="product__name--small">Nick name: {product.nickName}</h1>
<p className="product__description">Product description: {product.description}
</div>
<div>
)
JSX Rules
Trả về một phần tử duy nhất (chỉ một phần tử mẹ)
// not valid
return <h1>Hello world</h1><h2>Hi!</h2>
// valid with fragment.
return (
<>
<h1>Hello World</h1>
<h2>Hi!</h2>
</>
)
// Noted the parenthesis for multi-line formatting
Sử dụng className thay vì class
Ngoài ra, tất cả tên thuộc tính cần phải là camelCase
// not valid
return (
<div class="title">
Hello World
</div>
)
// valid
return (
<div className="title">
</div>
)
Đóng mọi phần tử
return (
<img src="http:example.com/image.jpg" />
<input type="text" name="first_name" />
)
Các Components lồng nhau
// Arrow function shorthand component
const Person = () => <h1>Mike Taylor</h1>
// Arrow function component
const Message = () => {
return <h1>Hello</h1>
}
// Function component
function HelloWorld(){
return (
<>
<Message />
<Person />
</>
)
}
Component CSS
(src/App.css)
h1 {
color: red;
}
(src / App.js)
Import tệp CSS
import './App.css'
function App(){
return <h1>Hello World</h1>
}
Inline CSS
function App(){
return <h1 style={{ color: 'red' }}>Hello World</h1>
}
Javascript trong JSX
- Bao quanh giữa {}
- Phải là một biểu thức (trả về một giá trị)
function App(){
const name = 'Mike'
return (
<>
<h1>Hello {name}</h1>
<p>{name === 'Mike' ? '(admin)': '(user)'}</p>
</>
)
}
Thuộc tính Component (Props)
function App()
return <Person name='Mike' age={29} />
}
const Person = (props) => {
return <h1>Name: {props.name}, Age: {props.age}</h1>
}
// or props object deconstructing
const Person = ({name, age}) => {
return <h1>Name: {name} Age: {age}</h1>
}
Children Props (slot)
function App()
return (
<Person name='Mike' age={29}>
Hi, this is a welcome message
</Person>
)
}
const Person = (props) => {
return (
<h1>Name: {props.name}, Age: {props.age}</h1>
<p>{props.children}</p>
)
}
// or props object deconstructing
const Person = ({name, age, children}) => {
return (
<h1>Name: {name} Age: {age}</h1>
<p>{children}</p>
)
}
Giá trị Props mặc định
const Person = ({name, age, children}) => {
return (
<h1>Name: {name} Age: {age}</h1>
<p>{children}</p>
)
}
Person.defaultProps = {
name: 'No name',
age: 0,
}
Danh sách
const people = [
{id: 1, name: 'Mike', age: 29},
{id: 2, name: 'Peter', age: 24},
{id: 3, name: 'John', age: 39},
]
function App(){
return (
people.map(person => {
return <Person name={person.name} age={person.age}/>
})
)
}
const Person = (props) => {
return (
<h1>Name: {props.name}, Age: {props.age}</h1>
)
}
Danh sách với từ khóa
function App(){
return (
people.map(person => {
return <Person key={person.id} name={person.name} age={person.age}/>
})
)
}
Deconstructing thuộc tính của object
function App(){
return people.map(person => <Person key={person.id} {...person} />)
}
const Person = (name, age) => {
return (
<h1>Name: {name}, Age: {age}</h1>
)
}
Nhấp vào Sự kiện
const clickHandler = () => alert('Hello World')
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={clickHandler}>Say Hi</button>
</>
)
}
hoặc inline
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={ () => alert('Hello World') }>Say Hi</button>
</>
)
}
Để chuyển các đối số, chúng ta cần sử dụng arrow function
const clickHandler = (message) => alert(message)
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={() => clickHandler('Hello World')}>Say Hi</button>
</>
)
}
e cho các đối số sự kiện
const clickHandler = (e) => console.log(e.target)
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={() => clickHandler('Hello World')}>Say Hi</button>
</>
)
}
Chuyển sự kiện từ con sang cha
function Todo({item, onDelete}) {
return (
<div>
{item}
<button onClick={() => onDelete(item)}
</div>
)
}
function Todos() {
const handleDelete = (todo) => {
const newTodos = todos.filter(item => item !== todo)
setTodos(() => newTodos)
}
return (
{todos.map(todo => (
<Todo item={todo} onDelete={handleDelete}/>
}
)
}
useState Hook
Mục đích của useState là xử lý dữ liệu phản ứng. Bất kỳ dữ liệu nào thay đổi trong ứng dụng được gọi là trạng thái. Và khi trạng thái thay đổi, bạn muốn phản ứng để cập nhật giao diện người dùng.
- Hook luôn bắt đầu bằng tiền tố 'use'
- Chỉ được gọi trong một component / hàm React
- Phải được gọi ở cấp cao nhất của một component chức năng
- Khai báo không thể được gọi có điều kiện
- useState trả về một mảng gồm 2: [giá trị trạng thái, đặt hàm trạng thái]
import React, {useState} from 'react';
const DisplayTitle = () => {
const [title, setTitle] = useState('This is the Title')
const handleClick = () => setTitle('New Title')
return <>
<h2>{title}</h2>
<button type="button" className="btn" onClick={handleClick}>
Change Title
</button>
</>
};
export default DisplayTitle;
useState với đối tượng
const DisplayTitle = () => {
const [person, setPerson] = useState({name: 'Mike', age: 29})
const handleClick = () => setPerson({...person, age: 35})
return <>
<h2>{title}</h2>
<button type="button" className="btn" onClick={handleClick}>
Change Age
</button>
</>
};
Dạng chức năng setState
function Counter() {
const [count, setCount] = useState(0)
// Use a function to set State
const increase = () => setCount(() => count + 1)
return (
<>
<h1>Counter</h1>
<p>{count}</p>
<button onClick={increase} className='btn'> + </button>
<button onClick={() => setCount(() => count - 1)} className='btn'> - </button>
</>
)
}
useEffect
Trong React, bạn có thể thực thi mã sau các sự kiện vòng đời hoặc các tác dụng phụ.
Theo mặc định, hàm useEffect được thực thi sau mỗi lần render. Sau đó, bạn có thể thực thi mã mỗi khi cập nhật component.
import React, { useEffect } from 'react';
function IncreaseValue() {
const [value, setValue] = useState(0)
useEffect(() => {
document.title = `New value: ${value}`
})
return <button onClick={() => setValue(value + 1)}>Increase</button>
}
useEffect có điều kiện
Có điều kiện cần phải được đặt bên trong hàm useEffect
useEffect(() => {
if (value > 0) {
document.title = `New value: ${value}`
}
})
Danh sách useEffect Dependency
Điều gì sẽ xảy ra nếu bạn muốn thực thi mã chỉ trong lần hiển thị đầu tiên hoặc chỉ khi một trạng thái cụ thể thay đổi? Bạn có thể sử dụng hàm useEffect và gửi một mảng phụ thuộc làm tham số.
useEffect sẽ chỉ chạy nếu trạng thái nằm trong Danh sách Dependency.
useEffect(() => {
document.title = `New value: ${value}`
}, [])
// Noted the empty array. useEffect will then only run once on initial render
useEffect(() => {
document.title = `New value: ${value}`
}, [value])
// Will run each time 'value' state change.
Chức năng dọn dẹp useEffect
Điều gì sẽ xảy ra nếu bạn muốn thực thi mã mỗi lần ngắt kết nối component?
Để thực thi mã chỉ khi một component được ngắt kết nối / hủy, bạn cần thêm câu lệnh 'return' vào hàm useEffect của mình.
useEffect(() => {
const timer = window.setInterval(() => {
setCount(count => count + 1)
}, 1000)
return () => clearInterval(timer)
}, [])
Mã 'clearInterval (bộ đếm thời gian)' sẽ chỉ được thực thi trước khi component bị xóa khỏi giao diện người dùng (ngắt kết nối)
Kết xuất có điều kiện
function DisplayGreeting() {
const [name, setName] = useState('Mike')
if (name === 'Mike') {
return <h1>Hello admin {name}</h1>
}
return <h1>Hello user {name}</h1>
}
Inline If-Else
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
Toán tử Logic &&.
Chỉ hiển thị nếu biểu thức đầu tiên là trung thực truthy = Not: 0, "", null, undefined và NaN
function DisplayUserInfo({active}) {
return (
<div>
{ active && <h1>User is active</h1>}
</div>
);
}
Nhiều inline If
<span className={count === 0 && 'text-gray-500' || count > 0 && 'text-green-500' || count < 0 && 'text-red-500'}>{count}</span>
Form
const UserForm = () => {
const [userName, setUserName] = useState('')
const handleSubmit = (e) => {
e.preventDefault()
console.log(userName)
}
return (
<>
<form onSubmit={handleSubmit}>
<input
value={userName}
onChange={(e) => setUserName(e.target.value)}
type="text" id="userName"
name="userName"
/>
<button type="submit">Submit</button>
</form>
</>
)
};
export default UserForm;
useRef
useRef chủ yếu được sử dụng để nhắm mục tiêu một phần tử DOM. Nhưng nó cũng có thể được sử dụng để giữ / bảo toàn một giá trị có thể thay đổi giữa mỗi lần hiển thị. useRef không kích hoạt kết xuất lại (giống như useState).
const UseRefBasics = () => {
const refContainer = useRef(null)
const handleSubmit = (e) => {
e.preventDefault()
console.log(refContainer.current.value)
}
useEffect(() => {
refContainer.current.focus()
}, [])
return (
<div>
<form className="form" onSubmit={handleSubmit}>
<div>
<input ref={refContainer} type="text" />
<button type="submit">Submit</button>
</div>
</form>
</div>
)
};
Nguồn bài viết tham khảo tại Dev.to
Tham khảo khóa học:
Web Frontend + React dành cho người mới bắt đầu - tại đây.
Hay khóa ReactJs 16 buổi - ở đây nè.
Bình luận