React(正在进行中)备忘单

2025-06-08

React(正在进行中)备忘单

我并不经常使用 React,因此每当我需要在 React 中做哪怕是最小的事情时,我都必须查看文档、教程或在论坛上发布问题。

这就是我决定做这个记忆辅助工具的原因,考虑到我的记忆力不是那么好,我想为什么不利用我所知道的关于 React 的所有概念来制作一个巨大的记忆辅助工具。

所以我可以时不时地阅读它,从而加强我对 React 的了解。

将所有这些放在一起需要几天的时间,因此每天我都会发布更新的 Cheat Sheet 版本,直到最终版本。

如果您有任何想法或建议,请不要犹豫,在评论部分发表。

React 备忘单(草稿第 2 天)

 

创建 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
Enter fullscreen mode Exit fullscreen mode

第一个 React 函数组件

  • 无需从“react”导入 React(自 React 17 起)
  • 首字母必须大写
  • 必须返回 JSX

(src/App.js)

// React component
function App(){
  return <h1>Hello World</h1>
} 

export default App;
Enter fullscreen mode Exit fullscreen mode

这个组件是如何渲染到浏览器的?主项目文件是 src/index.js,该文件中包含了渲染组件的指令。

ReactDOM.render(<App />, document.getElementById('root'))
Enter fullscreen mode Exit fullscreen mode

然后,App 组件将在 public/index.html 'root' div 内呈现

导入组件

组件将在单独的文件中创建。每个组件都需要导出,然后导入

function Greeting(){
    return <h1>Hello World</h2>
}
export default Greeting
Enter fullscreen mode Exit fullscreen mode

然后可以导入该组件

import Greeting from './Gretting'

function App(){
    return <Greeting />
}
Enter fullscreen mode Exit fullscreen mode

或名称导出...

export function Greeting(){
    return <h1>Hello World</h2>
}
Enter fullscreen mode Exit fullscreen mode

然后可以导入该组件

import {Greeting} from './Gretting'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

使用 className 而不是 class
并且所有属性名称都需要采用驼峰命名法

// not valid
return (
    <div class="title">
        Hello World
    </div>
)

// valid
return (
    <div className="title">
    </div>
)

Enter fullscreen mode Exit fullscreen mode

关闭每个元素

return (
    <img src="http:example.com/image.jpg" />
    <input type="text" name="first_name" />
)
Enter fullscreen mode Exit fullscreen mode

嵌套组件

// 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 />
      </>
  )
} 
Enter fullscreen mode Exit fullscreen mode

组件 CSS

(src/App.css)

h1 {
    color: red;
}

Enter fullscreen mode Exit fullscreen mode

(src/App.js)
导入 CSS 文件

import './App.css'

function App(){
  return <h1>Hello World</h1>
} 
Enter fullscreen mode Exit fullscreen mode

内联 CSS

function App(){
  return <h1 style={{ color: 'red' }}>Hello World</h1>
} 
Enter fullscreen mode Exit fullscreen mode

JSX 中的 JavaScript

  • 括在 {} 之间
  • 必须是一个表达式(返回一个值)
function App(){
    const name = 'Mike'
    return (
      <>
          <h1>Hello {name}</h1>
          <p>{name === 'Mike' ? '(admin)': '(user)'}</p>
      </>
    )
} 
Enter fullscreen mode Exit fullscreen mode

组件属性(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>
}
Enter fullscreen mode Exit fullscreen mode

儿童道具(插槽)

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

列表

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

带键列表(供 React 内部参考)

function App(){
    return (
        people.map(person => {
            return <Person key={person.id} name={person.name} age={person.age}/>
        })
     )
} 
Enter fullscreen mode Exit fullscreen mode

Props 对象解构

function App(){
  return people.map(person => <Person key={person.id} {...person} />)
}

const Person = (name, age) => {
  return (
      <h1>Name: {name}, Age: {age}</h1>
  )
} 
Enter fullscreen mode Exit fullscreen mode

点击事件

const clickHandler = () => alert('Hello World')
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={clickHandler}>Say Hi</button>
        </> 
    )
} 
Enter fullscreen mode Exit fullscreen mode

或内联...

function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={ () => alert('Hello World') }>Say Hi</button>
        </>
     )
} 
Enter fullscreen mode Exit fullscreen mode

要传递参数,我们需要使用箭头函数

const clickHandler = (message) => alert(message)
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={() => clickHandler('Hello World')}>Say Hi</button>
        </> 
    )
} 
Enter fullscreen mode Exit fullscreen mode

e 表示事件参数

const clickHandler = (e) => console.log(e.target)
function App(){
    return (
        <>
            <h1>Welcome to my app</h1>
            <button onClick={() => clickHandler('Hello World')}>Say Hi</button>
        </> 
    )
} 
Enter fullscreen mode Exit fullscreen mode

useState 钩子

  • 钩子总是以 use 前缀开头
  • 必须在组件/函数体中调用
  • 声明不能有条件地调用
  • 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;
Enter fullscreen mode Exit fullscreen mode

使用对象进行 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>
  </>
};
Enter fullscreen mode Exit fullscreen mode

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>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

useEffect

默认情况下,每次重新渲染后都会运行 useEffect

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

function IncreaseValue() {
    const [value, setValue] = useState(0)
    useEffect(() => {
        document.title = `New value: ${value}` 
    })
    return <button onClick={() => setValue(value + 1)}>Increase</button>
}
Enter fullscreen mode Exit fullscreen mode

有条件使用效果

条件需要放在 useEffect 函数中

useEffect(() => {
    if (value > 0) {
        document.title = `New value: ${value}` 
    }
})
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

useEffect 清理函数

这个 useEffect 返回函数会在每次组件卸载时执行。可以把它想象成组件卸载时的清理代码。

useEffect(() =>  { 
    const timer = window.setInterval(() => { 
        setCount(count => count + 1)
    }, 1000)
    return () => clearInterval(timer)
}, [])
Enter fullscreen mode Exit fullscreen mode

组件倍数回报

function DisplayGreeting() {
    const [name, setName] = useState('Mike')
    if (name === 'Mike') {
        return <h1>Hello admin {name}</h1> 
    }
    return <h1>Hello user {name}</h1> 
}
Enter fullscreen mode Exit fullscreen mode

形式

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;
Enter fullscreen mode Exit fullscreen mode

结论

今天就到这里。我们还有很多事情要做,明天见……如果你想确保不错过任何内容,请点击关注我!

我是 Twitter 新手,所以如果你想让我开心,
请关注我!:关注@justericchapman

鏂囩珷鏉ユ簮锛�https://dev.to/ericchapman/react-work-in-progress-cheat-sheet-13fb
PREV
有 Rails,然后是 Laravel,现在是 Adonis js
NEXT
NodeJS + Express 第 5 部分:路由和控制器