最强大的 React JS 速查表
React是一个用于构建用户界面的 JavaScript 库。本指南适用于 React v15 到 v16。
成分
import React from 'react'
import ReactDOM from 'react-dom'
class Hello extends React.Component {
render () {
return <div className='message-box'>
Hello {this.props.name}
</div>
}
}
const el = document.body
ReactDOM.render(<Hello name='John' />, el)
使用React.js jsfiddle开始 hacking。(或非官方的jsbin)
导入多个导出
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
class Hello extends Component {
...
}
特性
<Video fullscreen={true} autoplay={false} />
render () {
this.props.fullscreen
const { fullscreen, autoplay } = this.props
···
}
用于this.props
访问传递给组件的属性。
请参阅:属性
州
constructor(props) {
super(props)
this.state = { username: undefined }
}
this.setState({ username: 'rstacruz' })
render () {
this.state.username
const { username } = this.state
···
}
使用状态(this.state
)来管理动态数据。
使用Babel,你可以使用proposal-class-fields并摆脱构造函数
class Hello extends Component {
state = { username: undefined };
...
}
参见:州
获取书籍: 性能优化的 React 应用程序
嵌套
class Info extends Component {
render () {
const { avatar, username } = this.props
return <div>
<UserAvatar src={avatar} />
<UserProfile username={username} />
</div>
}
}
从 React v16.2.0 开始,片段可用于返回多个子项,而无需向 DOM 添加额外的包装节点。
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>
)
}
}
嵌套组件以分离关注点。
参见:组合组件
孩子们
<AlertBox>
<h1>You have pending notifications</h1>
</AlertBox>
class AlertBox extends Component {
render () {
return <div className='alert-box'>
{this.props.children}
</div>
}
}
孩子被当作财产传承下去children
。
默认值
设置默认道具
Hello.defaultProps = {
color: 'blue'
}
参见:defaultProps
设置默认状态
class Hello extends Component {
constructor (props) {
super(props)
this.state = { visible: true }
}
}
在 中设置默认状态constructor()
。
并且无需构造函数,使用带有proposal-class-fields 的Babel。
class Hello extends Component {
state = { visible: true }
}
参见:设置默认状态
其他组件
功能组件
function MyComponent ({ name }) {
return <div className='message-box'>
Hello {name}
</div>
}
函数组件没有状态。它们props
作为函数的第一个参数传递。
参见:函数和类组件
纯组件
import React, {PureComponent} from 'react'
class MessageBox extends PureComponent {
···
}
的性能优化版本React.Component
。如果 props/state 没有改变,则不会重新渲染。
参见:纯组件
组件 API
this.forceUpdate()
this.setState({ ... })
this.setState(state => { ... })
this.state
this.props
这些方法和属性可用于Component
实例。
参见:组件 API
生命周期
安装
方法 | 描述 |
---|---|
constructor (道具) |
渲染之前 |
componentWillMount() |
不要使用这个 # |
render() |
使成为# |
componentDidMount() |
渲染后(DOM 可用)# |
--- | --- |
componentWillUnmount() |
DOM 移除之前 |
--- | --- |
componentDidCatch() |
捕获错误(16+ ) |
在 上设置初始状态constructor()
。
在 上添加 DOM 事件处理程序、计时器(等)componentDidMount()
,然后在 上删除它们componentWillUnmount()
。
更新
方法 | 描述 |
---|---|
componentDidUpdate (prevProps、prevState、快照) |
在这里使用setState() ,但记得比较道具 |
shouldComponentUpdate (新属性,新状态) |
render() 如果返回 false,则跳过 |
render() |
使成为 |
componentDidUpdate (prevProps,prevState) |
在这里操作 DOM |
当父级更改属性 和 时调用.setState()
。初始渲染时不会调用这些。
参见:组件规格
挂钩(新)
州钩
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>
);
}
Hooks 是 React 16.8 中的新增功能。
参见:Hooks 概览
声明多个状态变量
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 (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
如果您熟悉 React 类生命周期方法,您可以将useEffect
Hook 视为componentDidMount
、componentDidUpdate
和的componentWillUnmount
组合。
默认情况下,React 在每次渲染后运行效果——包括第一次渲染。
构建你自己的钩子
定义 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';
}
效果还可以选择性地指定如何通过返回函数来“清理”。
使用 FriendStatus
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
参见:构建你自己的 Hooks
Hooks API 参考
另请参阅:Hooks 常见问题解答
基本钩子
钩 | 描述 |
---|---|
useState (初始状态) |
|
useEffect (() => { ... }) |
|
useContext (我的上下文) |
返回值React.createContext |
详细信息:基本 Hooks
附加钩子
钩 | 描述 |
---|---|
useReducer (reducer,initialArg,init) |
|
useCallback (() => { ... }) |
|
useMemo (() => { ... }) |
|
useRef (初始值) |
|
useImperativeHandle (引用,()=> {...}) |
|
useLayoutEffect |
与 相同useEffect ,但它在所有 DOM 变化后同步触发 |
useDebugValue (价值) |
在 React DevTools 中显示自定义钩子的标签 |
详细信息:附加挂钩
DOM 节点
参考
class MyComponent extends Component {
render () {
return <div>
<input ref={el => this.input = el} />
</div>
}
componentDidMount () {
this.input.focus()
}
}
允许访问 DOM 节点。
参见:Refs 和 DOM
DOM 事件
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 })
}
}
将函数传递给诸如的属性onChange
。
参见:活动
其他功能
转移道具
<VideoPlayer src="video.mp4" />
class VideoPlayer extends Component {
render () {
return <VideoEmbed {...this.props} />
}
}
向下传播src="..."
到子组件。
参见转移道具
顶级 API
React.createClass({ ... })
React.isValidElement(c)
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)
还有更多,但这些是最常见的。
参见:React 顶级 API
JSX 模式
样式简写
const style = { height: 10 }
return <div style={style}></div>
return <div style={{ margin: 0, padding: 0 }}></div>
参见:内联样式
内部 HTML
function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />
列表
class TodoList extends Component {
render () {
const { items } = this.props
return <ul>
{items.map(item =>
<TodoItem item={item} key={item.key} />)}
</ul>
}
}
始终提供key
属性。
条件语句
<Fragment>
{showMyComponent
? <MyComponent />
: <OtherComponent />}
</Fragment>
短路评估
<Fragment>
{showPopup && <Popup />}
...
</Fragment>
新功能
返回多个元素
您可以将多个元素作为数组或片段返回。
数组
render () {
// Don't forget the keys!
return [
<li key="A">First item</li>,
<li key="B">Second item</li>
]
}
片段
render () {
// Fragments don't require keys!
return (
<Fragment>
<li>First item</li>
<li>Second item</li>
</Fragment>
)
}
参见:片段和字符串
返回字符串
render() {
return 'Look ma, no spans!';
}
您可以只返回一个字符串。
参见:片段和字符串
错误
class MyComponent extends Component {
···
componentDidCatch (error, info) {
this.setState({ error })
}
}
通过 捕获错误componentDidCatch
。(React 16+)
门户
render () {
return React.createPortal(
this.props.children,
document.getElementById('menu')
)
}
这会渲染this.props.children
到 DOM 中的任何位置。
参见:门户
水合物
const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)
如果您要渲染ReactDOMServer的输出,请使用ReactDOM.hydrate
而不是使用。ReactDOM.render
参见:水合物
属性验证
PropTypes
import PropTypes from 'prop-types'
钥匙 | 描述 |
---|---|
any |
任何事物 |
基本的
钥匙 | 描述 |
---|---|
string |
|
number |
|
func |
功能 |
bool |
对还是错 |
枚举
钥匙 | 描述 |
---|---|
oneOf (任何) |
枚举类型 |
oneOfType (类型数组) |
联盟 |
大批
钥匙 | 描述 |
---|---|
array |
|
arrayOf (...) |
目的
钥匙 | 描述 |
---|---|
object |
|
objectOf (...) |
具有特定类型值的对象 |
instanceOf (...) |
类的实例 |
shape (...) |
元素
钥匙 | 描述 |
---|---|
element |
React 元素 |
node |
DOM 节点 |
必需的
钥匙 | 描述 |
---|---|
(···).isRequired |
必需的 |
基本类型
MyComponent.propTypes = {
email: PropTypes.string,
seats: PropTypes.number,
callback: PropTypes.func,
isClosed: PropTypes.bool,
any: PropTypes.any
}
必需类型
MyCo.propTypes = {
name: PropTypes.string.isRequired
}
元素
MyCo.propTypes = {
// React element
element: PropTypes.element,
// num, string, element, or an array of those
node: PropTypes.node
}
可枚举(oneOf)
MyCo.propTypes = {
direction: PropTypes.oneOf([
'left', 'right'
])
}
数组和对象
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
})
}
使用.array[Of]
,.object[Of]
,.instanceOf
,.shape
。
自定义验证
MyCo.propTypes = {
customProp: (props, key, componentName) => {
if (!/matchme/.test(props[key])) {
return new Error('Validation failed!')
}
}
}
学习 React 的其他资源:
完整的 React Native + Hooks 课程 [2020 版]
现代 React 训练营(Hooks、Context、NextJS、Router)
参考网站:https://devhints.io/react
文章来源:https://dev.to/bricourse/the-most-powerful-react-js-cheat-sheet-4ipd