Components
import React from 'react'
import ReactDOM from 'react-dom'
JavaScriptclass Hello extends React.Component {
render () {
return <div className='message-box'>
Hello {this.props.name}
</div>
}
}
JavaScriptconst el = document.body
ReactDOM.render(<Hello name='John' />, el)
JavaScriptImport multiple exports
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
JavaScriptclass Hello extends Component {
...
}
JavaScriptProperties
<Video fullscreen={true} autoplay={false} />
JavaScriptrender () {
this.props.fullscreen
const { fullscreen, autoplay } = this.props
···
}
JavaScriptDùng this.props để truy xuất giá trị truyền vào component.
States
constructor(props) {
super(props)
this.state = { username: undefined }
}
JavaScriptthis.setState({ username: 'rstacruz' })
JavaScriptrender () {
this.state.username
const { username } = this.state
···
}
JavaScriptDùng(this.state) để quản lý dữ liệu thay đổi bởi người dùng.
class Hello extends Component {
state = { username: undefined };
...
}
JavaScriptNesting
class Info extends Component {
render () {
const { avatar, username } = this.props
return <div>
<UserAvatar src={avatar} />
<UserProfile username={username} />
</div>
}
}
JavaScriptimport React, {
Component,
Fragment
} from 'react'
class Info extends Component {
render () {
const { avatar, username } = this.props
return (
<Fragment>
<UserAvatar src={avatar} />
<UserProfile username={username} />
</Fragment>
)
}
}
JavaScriptXem thêm : Composing Components
Children
<AlertBox>
<h1>You have pending notifications</h1>
</AlertBox>
JavaScriptclass AlertBox extends Component {
render () {
return <div className='alert-box'>
{this.props.children}
</div>
}
}
JavaScriptDefaults
Thiết lập giá trị mặc định cho props
Hello.defaultProps = {
color: 'blue'
}
JavaScriptXem 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 }
}
}
JavaScriptThiết lập giá trị mặc định cho state trong hàm constructor().
class Hello extends Component {
state = { visible: true }
}
JavaScriptXem thêm: Setting the default state
Những components khác
Functional components
function MyComponent ({ name }) {
return <div className='message-box'>
Hello {name}
</div>
}
JavaScriptXem thêm: Function and Class Components
Pure components
import React, {PureComponent} from 'react'
class MessageBox extends PureComponent {
···
}
JavaScriptPerformance-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()
JavaScriptthis.setState({ ... })
this.setState(state => { ... })
JavaScriptthis.state
this.props
JavaScriptXem thêm: Component API
Lifecycle
Mounting
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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>
);
}
JavaScriptNhữ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' }]);
// ...
}
JavaScriptEffect 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>
);
}
JavaScriptCó 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';
}
JavaScriptUse FriendStatus
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
JavaScriptXem thêm: Building Your Own Hooks
Hooks API Reference
Xem thêm: Hooks FAQ
Basic Hooks
| Hook | Description |
|---|---|
useState(initialState) | |
useEffect(() => { … }) | |
useContext(MyContext) | value returned from React.createContext |
Xem thêm: Basic Hooks
Additional Hooks
| Hook | Description |
|---|---|
useReducer(reducer, initialArg, init) | |
useCallback(() => { … }) | |
useMemo(() => { … }) | |
useRef(initialValue) | |
useImperativeHandle(ref, () => { … }) | |
useLayoutEffect | identical 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()
}
}
JavaScriptAllows 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 })
}
}
JavaScriptXem thêm: Events
Những features khác
Transferring props
<VideoPlayer src="video.mp4" />
JavaScriptclass VideoPlayer extends Component {
render () {
return <VideoEmbed {...this.props} />
}
}
JavaScriptXem thêm: Transferring props
Top-level API
React.createClass({ ... })
React.isValidElement(c)
JavaScriptReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
JavaScriptReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)
JavaScriptXem thêm: React top-level API
JSX patterns
Style shorthand
const style = { height: 10 }
return <div style={style}></div>
JavaScriptreturn <div style={{ margin: 0, padding: 0 }}></div>
JavaScriptXem thêm: Inline styles
Inner HTML
function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />
JavaScriptXem 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>
}
}
JavaScriptConditionals
<Fragment>
{showMyComponent
? <MyComponent />
: <OtherComponent />}
</Fragment>
JavaScriptShort-circuit evaluation
<Fragment>
{showPopup && <Popup />}
...
</Fragment>
JavaScriptNhữ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>
]
}
JavaScriptFragments
render () {
// Fragments don't require keys!
return (
<Fragment>
<li>First item</li>
<li>Second item</li>
</Fragment>
)
}
JavaScriptXem thêm: Fragments and strings
Returning strings
render() {
return 'Look ma, no spans!';
}
JavaScriptXem thêm: Fragments and strings
Errors
class MyComponent extends Component {
···
componentDidCatch (error, info) {
this.setState({ error })
}
}
JavaScriptCatch 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')
)
}
JavaScriptXem thêm: Portals
Hydration
const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)
JavaScriptXem thêm: Hydrate
Property validation
PropTypes
import PropTypes from 'prop-types'
JavaScriptXem thêm: Typechecking with PropTypes
| Key | Description |
|---|---|
any | Anything |
Basic
| Key | Description |
|---|---|
string | |
number | |
func | Function |
bool | True or false |
Enum
| Key | Description |
|---|---|
oneOf(any) | Enum types |
oneOfType(type array) | Union |
Array
| Key | Description |
|---|---|
array | |
arrayOf(…) |
Object
| Key | Description |
|---|---|
object | |
objectOf(…) | Object with values of a certain type |
instanceOf(…) | Instance of a class |
shape(…) |
Elements
| Key | Description |
|---|---|
element | React element |
node | DOM node |
Required
| Key | Description |
|---|---|
(···).isRequired | Required |
Basic types
MyComponent.propTypes = {
email: PropTypes.string,
seats: PropTypes.number,
callback: PropTypes.func,
isClosed: PropTypes.bool,
any: PropTypes.any
}
JavaScriptRequired types
MyCo.propTypes = {
name: PropTypes.string.isRequired
}
JavaScriptElements
MyCo.propTypes = {
// React element
element: PropTypes.element,
// num, string, element, or an array of those
node: PropTypes.node
}
JavaScriptEnumerables (oneOf)
MyCo.propTypes = {
direction: PropTypes.oneOf([
'left', 'right'
])
}
JavaScriptArrays and objects
MyCo.propTypes = {
list: PropTypes.array,
ages: PropTypes.arrayOf(PropTypes.number),
user: PropTypes.object,
user: PropTypes.objectOf(PropTypes.number),
message: PropTypes.instanceOf(Message)
}
JavaScriptMyCo.propTypes = {
user: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number
})
}
JavaScriptUse .array[Of], .object[Of], .instanceOf, .shape.
Custom validation
MyCo.propTypes = {
customProp: (props, key, componentName) => {
if (!/matchme/.test(props[key])) {
return new Error('Validation failed!')
}
}
}
JavaScriptTham khảo thêm: