React — JavaScript-библиотека с открытым исходным кодом, позволяющая быструю разработку интерфейсов для веб-приложений. В этой статье перечислены часто используемые конструкции и выражения для ReactJS.
Создание компонента
import React from 'react'
import ReactDOM from 'react-dom'
class Hello extends React.Component {
render () {
return
Hello {this.props.name}
}
}
const el = document.body
ReactDOM.render(, el)
Импорт нескольких компонентов
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
class Hello extends Component {
...
}
Свойства
render () {
this.props.fullscreen
const { fullscreen, autoplay } = this.props
···
}
Состояние
constructor(props) {
super(props)
this.state = { username: undefined }
}
this.setState({ username: 'rstacruz' })
render () {
this.state.username
const { username } = this.state
···
}
class Hello extends Component {
state = { username: undefined };
...
}
Вложенность
class Info extends Component {
render () {
const { avatar, username } = this.props
return
}
}
import React, {
Component,
Fragment
} from 'react'
class Info extends Component {
render () {
const { avatar, username } = this.props
return (
)
}
}
Дочерние компоненты
You have pending notifications
class AlertBox extends Component {
render () {
return
{this.props.children}
}
}
Установка свойств по умолчанию
Hello.defaultProps = {
color: 'blue'
}
Установка состояния по умолчанию
class Hello extends Component {
constructor (props) {
super(props)
this.state = { visible: true }
}
}
class Hello extends Component {
state = { visible: true }
}
Функциональные компоненты
function MyComponent ({ name }) {
return
Hello {name}
}
Чистые компоненты
import React, {PureComponent} from 'react'
class MessageBox extends PureComponent {
···
}
Компонент API
this.forceUpdate()
this.setState({ ... })
this.setState(state => { ... })
this.state
this.props
Монтаж компонента
constructor (props) Перед рендерингом, с props реквизитами
componentWillMount() Перед рендингом
render() Рендеринг
componentDidMount() После рендеринга
componentWillUnmount() Перед удалением DOM
componentDidCatch() Отлов ошибок
Обновление компонента
componentDidUpdate (prevProps, prevState, snapshot) Используйте setState() здесь и сравнить props реквизиты
shouldComponentUpdate (newProps, newState) Пропускает, render() если возвращается false
render()
componentDidUpdate (prevProps, prevState) Работайте с DOM здесь
Значение хуков
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
You clicked {count} times
setCount(count + 1)}>
Click me
);
}
Обновление нескольких состояний хуков
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}
Эффект хуков
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 (
You clicked {count} times
setCount(count + 1)}>
Click me
);
}
Создание своих хуков
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';
}
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
Ссылки в DOM узлах
class MyComponent extends Component {
render () {
return
this.input = el} />
}
componentDidMount () {
this.input.focus()
}
}
События DOM
class MyComponent extends Component {
render () {
this.onChange(event)} />
}
onChange (event) {
this.setState({ value: event.target.value })
}
}
Перенос реквизитов props
class VideoPlayer extends Component {
render () {
return
}
}
API верхнего уровня
React.createClass({ ... })
React.isValidElement(c)
ReactDOM.render(, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
ReactDOMServer.renderToString()
ReactDOMServer.renderToStaticMarkup()
Шаблоны JSX
const style = { height: 10 }
return
return
Внутренний HTML
function markdownify() { return "..."; }
Условия
{showMyComponent
?
: }
Оценка короткого замыкания
{showPopup && }
...
Списки
class TodoList extends Component {
render () {
const { items } = this.props
return
{items.map(item =>
)}
}
}
Возврат нескольких элементов
render () {
// Don't forget the keys!
return [
First item,
Second item
]
}
render () {
// Fragments don't require keys!
return (
First item
Second item
)
}
Возврат строк
render() {
return 'Look ma, no spans!';
}
Порталы
render () {
return React.createPortal(
this.props.children,
document.getElementById('menu')
)
}
Отлов ошибок
class MyComponent extends Component {
···
componentDidCatch (error, info) {
this.setState({ error })
}
}
Гидратация
const el = document.getElementById('app')
ReactDOM.hydrate(, el)
Основные типы
MyComponent.propTypes = {
email: PropTypes.string,
seats: PropTypes.number,
callback: PropTypes.func,
isClosed: PropTypes.bool,
any: PropTypes.any
}
Перечислимые (oneOf)
MyCo.propTypes = {
direction: PropTypes.oneOf([
'left', 'right'
])
}
Пользовательская проверка
MyCo.propTypes = {
customProp: (props, key, componentName) => {
if (!/matchme/.test(props[key])) {
return new Error('Validation failed!')
}
}
}
Обязательные типы
MyCo.propTypes = {
name: PropTypes.string.isRequired
}
Элементы
MyCo.propTypes = {
// React element
element: PropTypes.element,
// num, string, element, or an array of those
node: PropTypes.node
}
Массивы и объекты
MyCo.propTypes = {
list: PropTypes.array,
ages: PropTypes.arrayOf(PropTypes.number),
user: PropTypes.object,
user: PropTypes.objectOf(PropTypes.number),
message: PropTypes.instanceOf(Message)
}
MyCo.propTypes = {
user: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number
})
}
Типы реквизитов PropTypes
any | Anything |
Basic
string | |
number | |
func | Function |
bool | True or false |
Enum
oneOf(any) | Enum types |
oneOfType(type array) | Union |
Array
array | |
arrayOf(…) |
Object
object | |
objectOf(…) | Object with values of a certain type |
instanceOf(…) | Instance of a class |
shape(…) |
Elements
element | React element |
node | DOM node |
0 комментариев