React 备忘单(2021 年 6 月更新)
关注我!:关注@EricTheCoder_
我并不经常使用 React,因此每当我需要在 React 中做哪怕是最小的事情时,我都必须查看文档、教程或在论坛上发布问题。
这就是我决定做这个记忆辅助工具的原因,考虑到我的记忆力不是那么好,我想为什么不利用我所知道的关于 React 的所有概念来制作一个巨大的记忆辅助工具。
所以我可以时不时地阅读它,从而加强我对 React 的了解。
如果您有任何想法或建议,请不要犹豫,在评论部分发表。
React 速查表
创建 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
第一个 React 函数组件
- 无需从“react”导入 React(自 React 17 起)
- 首字母必须大写
- 必须返回 JSX
(src/App.js)
// React component
function App(){
return <h1>Hello World</h1>
}
export default App;
这个组件是如何渲染到浏览器的?主项目文件是 src/index.js,该文件中包含了渲染组件的指令。
ReactDOM.render(<App />, document.getElementById('root'))
然后,App 组件将在 public/index.html 'root' div 内呈现
导入组件
组件将在单独的文件中创建。每个组件都需要导出,然后导入
function Greeting(){
return <h1>Hello World</h2>
}
export default Greeting
然后可以导入该组件
import Greeting from './Gretting'
function App(){
return <Greeting />
}
或名称导出...
export function Greeting(){
return <h1>Hello World</h2>
}
然后可以导入该组件
import {Greeting} from './Gretting'
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 规则
返回单个元素(只有一个父元素)
// 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
使用 className 而不是 class
并且所有属性名称都需要采用驼峰命名法
// not valid
return (
<div class="title">
Hello World
</div>
)
// valid
return (
<div className="title">
</div>
)
关闭每个元素
return (
<img src="http:example.com/image.jpg" />
<input type="text" name="first_name" />
)
嵌套组件
// 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 />
</>
)
}
组件 CSS
(src/App.css)
h1 {
color: red;
}
(src/App.js)
导入 CSS 文件
import './App.css'
function App(){
return <h1>Hello World</h1>
}
内联 CSS
function App(){
return <h1 style={{ color: 'red' }}>Hello World</h1>
}
JSX 中的 JavaScript
- 括在 {} 之间
- 必须是一个表达式(返回一个值)
function App(){
const name = 'Mike'
return (
<>
<h1>Hello {name}</h1>
<p>{name === 'Mike' ? '(admin)': '(user)'}</p>
</>
)
}
组件属性(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>
}
儿童道具(插槽)
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>
)
}
默认 Props 值
const Person = ({name, age, children}) => {
return (
<h1>Name: {name} Age: {age}</h1>
<p>{children}</p>
)
}
Person.defaultProps = {
name: 'No name',
age: 0,
}
列表
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>
)
}
带键列表(供 React 内部参考)
function App(){
return (
people.map(person => {
return <Person key={person.id} name={person.name} age={person.age}/>
})
)
}
Props 对象解构
function App(){
return people.map(person => <Person key={person.id} {...person} />)
}
const Person = ({name, age}) => {
return (
<h1>Name: {name}, Age: {age}</h1>
)
}
点击事件
const clickHandler = () => alert('Hello World')
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={clickHandler}>Say Hi</button>
</>
)
}
或内联...
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={ () => alert('Hello World') }>Say Hi</button>
</>
)
}
要传递参数,我们需要使用箭头函数
const clickHandler = (message) => alert(message)
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={() => clickHandler('Hello World')}>Say Hi</button>
</>
)
}
e 表示事件参数
const clickHandler = (e) => console.log(e.target)
function App(){
return (
<>
<h1>Welcome to my app</h1>
<button onClick={clickHandler}>Say Hi</button>
</>
)
}
将事件从子级传递到父级
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 钩子
useState 的目的是处理响应式数据。应用程序中任何发生变化的数据都称为状态。当状态发生变化时,你需要响应式地更新 UI。
- Hook 总是以 'use' 前缀开头
- 必须仅在 React 组件/函数中调用
- 必须在功能组件的顶层调用
- 声明不能有条件地调用
- useState 返回一个包含 2 个元素的数组:[状态值,设置状态函数]
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
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>
</>
};
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
在 React 中,您可能希望在生命周期事件或副作用之后执行代码。
默认情况下,useEffect 函数在每次重新渲染后执行。这样,你就可以在每次组件更新时执行代码。
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 函数中
useEffect(() => {
if (value > 0) {
document.title = `New value: ${value}`
}
})
useEffect 依赖列表
如果您只想在首次渲染时或特定状态发生变化时执行代码,该怎么办?您可以使用 useEffect 函数并发送依赖项数组作为参数。
仅当状态在依赖项列表中时,useEffect 才会运行。
如果列表为空 [],则 useEffect 仅在初始渲染时运行。
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.
useEffect 清理函数
如果您想在每次卸载组件时执行代码怎么办?
要仅在组件卸载/销毁时执行代码,您需要在 useEffect 函数中添加“return”语句。
useEffect(() => {
const timer = window.setInterval(() => {
setCount(count => count + 1)
}, 1000)
return () => clearInterval(timer)
}, [])
代码“clearInterval(timer)”仅在组件从 UI 中移除(卸载)之前执行
条件渲染
function DisplayGreeting() {
const [name, setName] = useState('Mike')
if (name === 'Mike') {
return <h1>Hello admin {name}</h1>
}
return <h1>Hello user {name}</h1>
}
内联 If-Else
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
内联逻辑 && 运算符。
仅当第一个表达式为真时才显示
truthy = Not : 0、""、null、undefined 和 NaN
function DisplayUserInfo({active}) {
return (
<div>
{ active && <h1>User is active</h1>}
</div>
);
}
多个内联 If
<span className={count === 0 && 'text-gray-500' || count > 0 && 'text-green-500' || count < 0 && 'text-red-500'}>{count}</span>
形式
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 主要用于定位 DOM 元素。但它也可用于在每次渲染之间保存/保留可变值。useRef 不会触发重新渲染(例如 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>
)
};
结论
今天就到这里。我们还有很多事情要做,明天见……如果你想确保不错过任何内容,请点击关注我!
关注我!:关注@EricTheCoder_
文章来源:https://dev.to/ericchapman/react-cheat-sheet-updated-may-2021-1mcd