HocWeb.VN
  • Frontend
  • Backend
  • Tools
Thẻ
AI Tool (1) chatGPT (1) cheat sheets (1) framework (1) node.js (2) postgresql (1) react js (1) ubuntu (1) vps (1)
Vũ Đức Phương

Fullstack Developer

Likes
Subscribers
HocWeb.vn
  • Frontend
  • Backend
  • Tools
  • Frontend

Vài thủ thuật hữu ích khi làm việc với React JS

  • 15/01/2024
  • Vũ Đức Phương
Total
0
Shares
0
0
0
0
Mục lục Hide
    1. Components
    2. Import multiple exports
    3. Properties
    4. States
    5. Nesting
    6. Children
  1. Defaults
    1. Thiết lập giá trị mặc định cho props
    2. Thiết lập giá trị mặc định cho state
  2. Những components khác
    1. Functional components
    2. Pure components
    3. Component API
  3. Lifecycle
    1. Mounting
    2. Updating
  4. Hooks (New)
    1. State Hook
    2. Declaring multiple state variables
    3. Effect hook
    4. Building your own hooks
    5. Hooks API Reference
  5. DOM nodes
    1. References
    2. DOM Events
  6. Những features khác
    1. Transferring props
    2. Top-level API
  7. JSX patterns
    1. Style shorthand
    2. Inner HTML
    3. Lists
    4. Conditionals
    5. Short-circuit evaluation
  8. Những features mới
    1. Returning multiple elements
    2. Returning strings
    3. Errors
    4. Portals
    5. Hydration
  9. Property validation
    1. PropTypes
    2. Basic types
    3. Required types
    4. Elements
    5. Enumerables (oneOf)
    6. Arrays and objects
    7. Custom validation

Components

import React from 'react'
import ReactDOM from 'react-dom'
JavaScript
class Hello extends React.Component {
  render () {
    return <div className='message-box'>
      Hello {this.props.name}
    </div>
  }
}
JavaScript
const el = document.body
ReactDOM.render(<Hello name='John' />, el)
JavaScript

Import multiple exports

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
JavaScript
class Hello extends Component {
  ...
}
JavaScript

Properties

<Video fullscreen={true} autoplay={false} />
JavaScript
render () {
  this.props.fullscreen
  const { fullscreen, autoplay } = this.props
  ···
}
JavaScript

Dùng this.props để truy xuất giá trị truyền vào component.

States

constructor(props) {
  super(props)
  this.state = { username: undefined }
}
JavaScript
this.setState({ username: 'rstacruz' })
JavaScript
render () {
  this.state.username
  const { username } = this.state
  ···
}
JavaScript

Dùng(this.state) để quản lý dữ liệu thay đổi bởi người dùng.

class Hello extends Component {
  state = { username: undefined };
  ...
}


JavaScript

Nesting

class Info extends Component {
  render () {
    const { avatar, username } = this.props

    return <div>
      <UserAvatar src={avatar} />
      <UserProfile username={username} />
    </div>
  }
}
JavaScript

import React, {
  Component,
  Fragment
} from 'react'

class Info extends Component {
  render () {
    const { avatar, username } = this.props

    return (
      <Fragment>
        <UserAvatar src={avatar} />
        <UserProfile username={username} />
      </Fragment>
    )
  }
}
JavaScript

Xem thêm : Composing Components

Children

<AlertBox>
  <h1>You have pending notifications</h1>
</AlertBox>
JavaScript
class AlertBox extends Component {
  render () {
    return <div className='alert-box'>
      {this.props.children}
    </div>
  }
}
JavaScript

Defaults

Thiết lập giá trị mặc định cho props

Hello.defaultProps = {
  color: 'blue'
}
JavaScript

Xem thêm: defaultProps

Thiết lập giá trị mặc định cho state

class Hello extends Component {
  constructor (props) {
    super(props)
    this.state = { visible: true }
  }
}
JavaScript

Thiết lập giá trị mặc định cho state trong hàm constructor().

class Hello extends Component {
  state = { visible: true }
}
JavaScript

Xem thêm: Setting the default state

Những components khác

Functional components

function MyComponent ({ name }) {
  return <div className='message-box'>
    Hello {name}
  </div>
}
JavaScript

Xem thêm: Function and Class Components

Pure components

import React, {PureComponent} from 'react'

class MessageBox extends PureComponent {
  ···
}
JavaScript

Performance-optimized version of React.Component. Sẽ không render lại nếu props/state không thay đổi.

Xem thêm: Pure components

Component API

this.forceUpdate()
JavaScript
this.setState({ ... })
this.setState(state => { ... })
JavaScript
this.state
this.props
JavaScript

Xem thêm: Component API

Lifecycle

Mounting

MethodDescription
constructor (props)Before rendering #
componentWillMount()Don’t use this #
render()Render #
componentDidMount()After rendering (DOM available) #
——
componentWillUnmount()Before DOM removal #
——
componentDidCatch()Catch errors (16+) #

Updating

MethodDescription
componentDidUpdate (prevProps, prevState, snapshot)Use setState() here, but remember to compare props
shouldComponentUpdate (newProps, newState)Skips render() if returns false
render()Render
componentDidUpdate (prevProps, prevState)Operate on the DOM here

Những hàm này sẽ được gọi khi component cha bị thay đổi giá trị “properties” hoặc gọi hàm  .setState(). Những hàm này sẽ không được thực thi khi lần đầu render.

Xem thêm: Component specs

Hooks (New)

State Hook

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
JavaScript

Những hooks này được thêm vào kể từ version React 16.8.

Xem thêm: Hooks at a Glance

Declaring multiple state variables

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}
JavaScript

Effect hook

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`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
JavaScript

Có thể xem useEffect Hook là sự kết hợp của componentDidMount, componentDidUpdate, componentWillUnmount.

Building your own hooks

Define FriendStatus

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  }, [props.friend.id]);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}
JavaScript

Use FriendStatus

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}
JavaScript

Xem thêm: Building Your Own Hooks

Hooks API Reference

Xem thêm: Hooks FAQ

Basic Hooks

HookDescription
useState(initialState)
useEffect(() => { … })
useContext(MyContext)value returned from React.createContext

Xem thêm: Basic Hooks

Additional Hooks

HookDescription
useReducer(reducer, initialArg, init)
useCallback(() => { … })
useMemo(() => { … })
useRef(initialValue)
useImperativeHandle(ref, () => { … })
useLayoutEffectidentical to useEffect, but it fires synchronously after all DOM mutations
useDebugValue(value)display a label for custom hooks in React DevTools

Xem thêm: Additional Hooks

DOM nodes

References

class MyComponent extends Component {
  render () {
    return <div>
      <input ref={el => this.input = el} />
    </div>
  }

  componentDidMount () {
    this.input.focus()
  }
}
JavaScript

Allows access to DOM nodes.

See: Refs and the DOM

DOM Events

class MyComponent extends Component {
  render () {
    <input type="text"
        value={this.state.value}
        onChange={event => this.onChange(event)} />
  }

  onChange (event) {
    this.setState({ value: event.target.value })
  }
}
JavaScript

Xem thêm: Events

Những features khác

Transferring props

<VideoPlayer src="video.mp4" />
JavaScript
class VideoPlayer extends Component {
  render () {
    return <VideoEmbed {...this.props} />
  }
}
JavaScript

Xem thêm: Transferring props

Top-level API

React.createClass({ ... })
React.isValidElement(c)
JavaScript
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
JavaScript
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)
JavaScript

Xem thêm: React top-level API

JSX patterns

Style shorthand

const style = { height: 10 }
return <div style={style}></div>
JavaScript
return <div style={{ margin: 0, padding: 0 }}></div>
JavaScript

Xem thêm: Inline styles

Inner HTML

function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />
JavaScript

Xem thêm: Dangerously set innerHTML

Lists

class TodoList extends Component {
  render () {
    const { items } = this.props

    return <ul>
      {items.map(item =>
        <TodoItem item={item} key={item.key} />)}
    </ul>
  }
}
JavaScript

Conditionals

<Fragment>
  {showMyComponent
    ? <MyComponent />
    : <OtherComponent />}
</Fragment>
JavaScript

Short-circuit evaluation

<Fragment>
  {showPopup && <Popup />}
  ...
</Fragment>
JavaScript

Những features mới

Returning multiple elements

Arrays

render () {
  // Don't forget the keys!
  return [
    <li key="A">First item</li>,
    <li key="B">Second item</li>
  ]
}
JavaScript

Fragments

render () {
  // Fragments don't require keys!
  return (
    <Fragment>
      <li>First item</li>
      <li>Second item</li>
    </Fragment>
  )
}
JavaScript

Xem thêm: Fragments and strings

Returning strings

render() {
  return 'Look ma, no spans!';
}
JavaScript

Xem thêm: Fragments and strings

Errors

class MyComponent extends Component {
  ···
  componentDidCatch (error, info) {
    this.setState({ error })
  }
}
JavaScript

Catch errors thông qua componentDidCatch. (React 16+)

Xem thêm: Error handling in React 16

Portals

render () {
  return React.createPortal(
    this.props.children,
    document.getElementById('menu')
  )
}
JavaScript

Xem thêm: Portals

Hydration

const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)
JavaScript

Xem thêm: Hydrate

Property validation

PropTypes

import PropTypes from 'prop-types'
JavaScript

Xem thêm: Typechecking with PropTypes

KeyDescription
anyAnything

Basic

KeyDescription
string
number
funcFunction
boolTrue or false

Enum

KeyDescription
oneOf(any)Enum types
oneOfType(type array)Union

Array

KeyDescription
array
arrayOf(…)

Object

KeyDescription
object
objectOf(…)Object with values of a certain type
instanceOf(…)Instance of a class
shape(…)

Elements

KeyDescription
elementReact element
nodeDOM node

Required

KeyDescription
(···).isRequiredRequired

Basic types

MyComponent.propTypes = {
  email:      PropTypes.string,
  seats:      PropTypes.number,
  callback:   PropTypes.func,
  isClosed:   PropTypes.bool,
  any:        PropTypes.any
}
JavaScript

Required types

MyCo.propTypes = {
  name:  PropTypes.string.isRequired
}
JavaScript

Elements

MyCo.propTypes = {
  // React element
  element: PropTypes.element,

  // num, string, element, or an array of those
  node: PropTypes.node
}
JavaScript

Enumerables (oneOf)

MyCo.propTypes = {
  direction: PropTypes.oneOf([
    'left', 'right'
  ])
}
JavaScript

Arrays and objects

MyCo.propTypes = {
  list: PropTypes.array,
  ages: PropTypes.arrayOf(PropTypes.number),
  user: PropTypes.object,
  user: PropTypes.objectOf(PropTypes.number),
  message: PropTypes.instanceOf(Message)
}
JavaScript
MyCo.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string,
    age:  PropTypes.number
  })
}
JavaScript

Use .array[Of], .object[Of], .instanceOf, .shape.

Custom validation

MyCo.propTypes = {
  customProp: (props, key, componentName) => {
    if (!/matchme/.test(props[key])) {
      return new Error('Validation failed!')
    }
  }
}
JavaScript

Tham khảo thêm:

The Complete React Native + Hooks Course [2020 Edition]

The Modern React Bootcamp (Hooks, Context, NextJS, Router)

Total
0
Shares
Share 0
Tweet 0
Pin it 0
Share 0
Cùng chủ đề
  • cheat sheets
  • react js
Vũ Đức Phương

Chia sẻ kiến thức lập trình web và NodeJs.

Previous Article
  • Backend

Top 4 Node.js Frameworks để xây dựng ứng dụng web 2024

  • 11/01/2024
  • Vũ Đức Phương
View Post
Next Article
  • Backend

Hướng dẫn deploy Node.js lên VPS

  • 15/01/2024
  • Vũ Đức Phương
View Post
Có thể bạn sẽ thích

Bài mới

  • Top 9 cộng cụ AI – chatGPT hữu ích cho việc phát triển web
  • Hướng dẫn deploy Node.js lên VPS
  • Vài thủ thuật hữu ích khi làm việc với React JS
  • Top 4 Node.js Frameworks để xây dựng ứng dụng web 2024
  • Top 5 công cụ quản lý PosgreSQL tốt nhất 2024

Comments

Không có bình luận nào để hiển thị.
Bài viết nổi bật
  • 1
    Top 9 cộng cụ AI – chatGPT hữu ích cho việc phát triển web
    • 16/01/2024
  • 2
    Hướng dẫn deploy Node.js lên VPS
    • 15/01/2024
  • 3
    Vài thủ thuật hữu ích khi làm việc với React JS
    • 15/01/2024
  • 4
    Top 4 Node.js Frameworks để xây dựng ứng dụng web 2024
    • 11/01/2024
  • 5
    Top 5 công cụ quản lý PosgreSQL tốt nhất 2024
    • 20/11/2019
Thẻ
AI Tool chatGPT cheat sheets framework node.js postgresql react js ubuntu vps
Chủ đề
  • Backend (2)
  • Database (1)
  • Frontend (1)
  • Tools (2)
Tác giả
Vũ Đức Phương
Chia sẻ kiến thức lập trình web và NodeJs.

Đăng ký nhận tin mới nhất qua email

hocweb.vn
  • Frontend
  • Backend
  • Tools
Chia sẻ kiến thức, kinh nghiệm, tài nguyên học lập trình web.

Input your search keywords and press Enter.