Zde je Cheatsheet React v16+ (PDF/JPEG/Vlastní témata)

Najděte mě na médiu
Připojte se k mému newsletteru

Přiveďte mě k cheat sheet

Někdy může vytvoření rychlého rozhraní pomocí Reactu trvat třicet minut. Ale někdy to může také trvat hodiny, může to být ovlivněno mnoha důvody.

Pokud často zapomínáte názvy metod, vlastností nebo funkcí, které poskytují, může být nepříjemné opustit editor kódu jen kvůli vyhledávání na Googlu. Je však opravdu tak těžké napsat pár písmen a získat požadované odpovědi? No, rozhodně ne. Ale pokud se to stane více než jednou, možná je čas získat cheat sheet do vašeho vlastnictví, abyste už nemuseli opouštět svůj editor kódu. Mít vedle sebe cheat sheet vám z dlouhodobého hlediska jistě ušetří nějaký čas!

Zde je cheat list, který můžete použít:

Přiveďte mě k cheat sheet

Zatímco se díváte na cheat sheet, mějte na paměti, že můžete:

  1. Vygenerujte cheat sheet do PDF nebo PNG ke stažení, nebo si můžete stránku uložit do záložek a vrátit se k ní později.

  2. Pokud se vám nelíbí, jak jsou sloupce seřazeny, můžete je přetáhnout a znovu uspořádat, než uložíte cheat sheet.

  3. Můžete si vybrat libovolné z motivů syntaxe kódu ve výběrovém poli, které chcete vygenerovat v cheat sheetu (můžete si vybrat asi 25 témat):

Pokračuji a dám to do veřejného úložiště, pokud to někdo potřebuje. Také jsem to začal včera, takže to možná ještě není dokonalý cheat.

Mým cílem bylo také vměstnat toto vše na jednu stránku, ale informací bylo příliš mnoho. Pokud má někdo nějaké návrhy, které části vyměnit/odebrat, dejte mi vědět.

A změny přetrvají i po zavření prohlížeče, takže nemusíte vše opakovat.

Zde je úplný seznam toho, co je zatím v cheat sheetu (budu ho průběžně aktualizovat):

Fragmenty

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

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

Typy návratů

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 />,
]

Hranice chyb (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>
)

Statické metody

// 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) {...}
}

Stavy komponent

// 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} />

Komponenty vykreslování

// 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} />

Výchozí rekvizity

// 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} />
  }
}

Další exporty 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)

Import

// 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'

Události ukazatele (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} />
}

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>
)

React Profiler (React v16.9)

const App = () => (
  <React.StrictMode>
    <div>
      <MyComponent />
      <OtherComponent />
    </div>
  </React.StrictMode>
)

Synchronní / Asynchronní act Testovací nástroj (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
  })
})

Přiveďte mě k cheat sheet

Závěr

A tím končí tento příspěvek! Doufám, že to bylo užitečné a v budoucnu se budete těšit na další!

Najděte mě na médiu
Připojte se k mému newsletteru