这是 React v16+ 备忘单(PDF/JPEG/自定义主题)

2025-05-25

这是 React v16+ 备忘单(PDF/JPEG/自定义主题)

在Medium上找到我
加入我的时事通讯

带我去看备忘单

有时使用 React 创建一个快速界面可能需要三十分钟,但有时也可能需要几个小时,这可能受到多种原因的影响。

如果你经常忘记方法、属性的名称或它们提供的功能,那么为了谷歌搜索而不得不离开代码编辑器就很烦人。然而,输入几个字母就能得到你想要的答案真的那么难吗?当然不是。但如果这种情况不止一次发生,那么也许是时候准备一张速查表了,这样你就不用再离开代码编辑器了。从长远来看,手边有一张速查表肯定会节省你的时间!

以下是您可以使用的备忘单:

React v16 备忘单

带我去看备忘单

当你查看备忘单时,请记住你可以:

  1. 将备忘单生成为可下载的 PDF 或 PNG 格式,或者您可以将该页面添加为书签并在稍后返回。

  2. 如果您不喜欢列的排序方式,您可以在保存备忘单之前拖动并重新排序它们。

  3. 您可以在选择框中选择任意代码语法主题在备忘单中生成(大约有 25 个主题可供选择):

选择框

如果有人需要的话,我会把它放到公开仓库里。我昨天才开始做,所以它可能还不是一份完美的备忘单。

另外,我本来想把所有内容都放在一页纸里,但信息量太大了。如果有人对哪些部分需要替换/删除有什么建议,请随时告诉我。

关闭浏览器后更改仍会保留,因此您不必重新执行所有操作。

以下是迄今为止备忘单中内容的完整列表(我会随着时间的推移不断更新备忘单):

片段

// Does not support key attribute
const App = () => (
  <>
    <MyComponent />
  </>
)

// Supports key attribute
const App = () => (
  <React.Fragment key="abc123">
    <MyComponent />
  </React.Fragment>
)
Enter fullscreen mode Exit fullscreen mode

返回类型

const App = () => 'a basic string' // string
const App = () => 1234567890 // number
const App = () => true // boolean
const App = () => null // null
const App = () => <div /> // react element
const App = () => <MyComponent /> // component
const App = () => [
  // array
  'a basic string',
  1234567890,
  true,
  null,
  <div />,
  <MyComponent />,
]
Enter fullscreen mode Exit fullscreen mode

错误边界(React v16.0)

class MyErrorBoundary extends React.Component {
  state = { hasError: false }
  componentDidCatch(error, info) {...}
  render() {
    if (this.state.hasError) return <SomeErrorUI />
    return this.props.children
  }
}

const App = () => (
  <MyErrorBoundary>
    <Main />
  </MyErrorBoundary>
)
Enter fullscreen mode Exit fullscreen mode

静态方法

// Returning object = New props require state update
// Returning null = New props do not require state update
class MyComponent extends React.Component {
  static getDerivedStateFromProps(props, state) {...}
  state = {...}
}

// Return value is passed as 3rd argument to componentDidUpdate
class MyComponent extends React.Component {
  static getSnapshotBeforeUpdate(prevProps, prevState) {...}
}

// Listening to context from a class component
import SomeContext from '../SomeContext'
class MyCompmonent extends React.Component {
  static contextType = SomeContext
  componentDidMount() { console.log(this.context) }
}

// Enables rendering fallback UI before render completes
class MyComponent extends React.Component {
  state getDerivedStateFromError() {...}
  state = { error: null }
  componentDidCatch(error, info) {...}
}
Enter fullscreen mode Exit fullscreen mode

组件状态

// Class component state
class MyComponent extends React.Component {
  state = { loaded: false }
  componentDidMount = () => this.setState({ loaded: true })
  render() {
    if (!this.state.loaded) return null
    return <div {...this.props} />
  }
}

// Function component state (useState/useReducer)
const MyComponent = (props) => {
  // With useState
  const [loaded, setLoaded] = React.useState(false)
  // With useReducer
  const [state, dispatch] = React.useReducer(reducer, initialState)
  if (!loaded) return null
  React.useEffect(() => void setLoaded(true))
  return <div {...props} />
Enter fullscreen mode Exit fullscreen mode

渲染组件

// Ways to render Card
const Card = (props) => <div {...props} />

const App = ({ items = [] }) => {
  const renderCard = (props) => <Card {...props} />
  return items.map(renderCard)
  // or return items.map((props) => renderCard(props))
}

const App = (props) => <Card {...props} />

class App extends React.Component {
  render() {
    return <Card {...this.props} />
  }
}

const MyComp = ({ component: Component }) => <Component />
const App = () => <MyComp component={Card} />
Enter fullscreen mode Exit fullscreen mode

默认道具

// Function component
const MyComponent = (props) => <div {...props} />
MyComponent.defaultProps = { fruit: 'apple' }

// Class component
class MyComponent extends React.Component {
  static defaultProps = { fruit: 'apple' }
  render() {
    return <div {...this.props} />
  }
}
Enter fullscreen mode Exit fullscreen mode

其他 React 导出

// createContext (React v16.3)
const WeatherContext = React.createContext({ day: 3 })
const App = ({ children }) => {
  const [weather, setWeather] = React.useState(null)
  const [error, setError] = React.useState(null)
  React.useEffect(() => {
    api.getWeather(...)
      .then(setWeather)
      .catch(setError)
  }, [])
  const contextValue = { weather, error }
  return (
    <WeatherContext.Provider value={contextValue}>
      {children}
    </WeatherContext.Provider>
  )
}
const SomeChild = () => {
  const { weather } = React.useContext(WeatherContext)
  console.log(weather)
  return null
}

// createRef (Obtain a reference to a react node) (React v16.3)
const App = () => {
  const ref = React.createRef()
  React.useEffect(() => { console.log(ref.current) }, [])
  return <div ref={ref} />
}

// forwardRef (Pass the ref down to a child) (React v16.3)
const Remote = React.forwardRef((props, ref) => (
  <div ref={ref} {...props} />
))
const App = () => {
  const ref = React.createRef()
  return <Remote ref={ref} />
}

// memo (Optimize your components to avoid wasteful renders) (React v16.6)
const App = () => {...}
const propsAreEqual = (props, nextProps) => {
  return props.id === nextProps.id
} // Does not re-render if id is the same
export default React.memo(App, propsAreEqual)

Enter fullscreen mode Exit fullscreen mode

输入

// default export
const App = (props) => <div {...props} />
export default App
import App from './App'

// named export
export const App = (props) => <div {...props} />
import { App } from './App'
Enter fullscreen mode Exit fullscreen mode

指针事件 (React v16.4)

onPointerUp           onPointerDown
onPointerMove         onPointerCancel
onGotPointerCapture   onLostPointerCapture
onPointerEnter        onPointerLeave
onPointerOver         onPointerOut

const App = () => {
  const onPointerDown = (e) => console.log(e.pointerId)
  return <div onPointerDown={onPointerDown} />
}
Enter fullscreen mode Exit fullscreen mode

React Suspense/Lazy(React v16.6)

// lazy -> Dynamic import. Reduces bundle size
// + Code splitting
const MyComponent = React.lazy(() => import('./MyComponent))
const App = () => <MyComponent />

// Suspend rendering while components are waiting for something
// + Code splitting
import LoadingSpinner from '../LoadingSpinner'
const App = () => (
  <React.Suspense fallback={<LoadingSpinner />}>
    <MyComponent />
  </React.Suspense>
)
Enter fullscreen mode Exit fullscreen mode

React Profiler(React v16.9)

const App = () => (
  <React.StrictMode>
    <div>
      <MyComponent />
      <OtherComponent />
    </div>
  </React.StrictMode>
)
Enter fullscreen mode Exit fullscreen mode

同步/异步act测试实用程序 (React v16.9)

import { act } from 'react-dom/test-utils'
import MyComponent from './MyComponent'
const container = document.createElement('div')

// Synchronous
it('renders and adds new item to array', () => {
  act(() => {
    ReactDOM.render(<MyComponent />, container)
  })
  const btn = container.querySelector('button')
  expect(btn.textContent).toBe('one item')
  act(() => {
    button.dispatchEvent(new MouseEvent('click', { bubbles: true }))
  })
  expect(btn.textContent).toBe('two items')
})

// Asynchronous
it('does stuff', async () => {
  await act(async () => {
    // code
  })
})
Enter fullscreen mode Exit fullscreen mode

带我去看备忘单

结论

这篇文章到此结束!希望你觉得这篇文章有用,并期待未来有更多精彩内容!

在Medium上找到我
加入我的时事通讯

文章来源:https://dev.to/jsmanifest/a-react-v16-cheatsheet-24f9
PREV
React Hooks 的强大之处 - 在 React 中仅使用此功能创建应用程序
NEXT
你应该知道的 8 个 React 应用实用实践