다음은 React v16 + 치트 시트입니다 (PDF / JPEG / 사용자 정의 테마).
본문
때로는 React를 사용하여 빠른 인터페이스를 만드는 데 30 분이 걸릴 수 있습니다. 그러나 때로는 여러 가지 이유로 인해 시간이 걸릴 수도 있습니다.
메소드, 속성 또는 제공하는 기능의 이름을 잊어 버린 경우 Google 검색을 위해 코드 편집기를 떠나야 하는 것이 짜증이 날 수 있습니다. 그러나 실제로 두 글자를 입력하고 원하는 답변을 얻는 것이 어렵습니까? 글쎄요. 그러나 이것이 두 번 이상 발생하면 코드 편집기를 더 이상 떠날 필요가 없도록 치트 시트를 소유해야 할 때입니다. 옆에 컨닝 페이퍼가 있으면 장기적으로 시간을 절약 할 수 있습니다!
https://dev.to/jsmanifest/a-react-v16-cheatsheet-24f9
치트 시트를 보고 있는 동안 다음을 수행 할 수 있습니다.
- 치트 시트를 다운로드 가능한 PDF 또는 PNG로 생성하거나 페이지를 책갈피에 추가하여 나중에 다시 올 수 있습니다.
- 열 순서가 마음에 들지 않으면 치트 시트를 저장하기 전에 열을 끌어 순서를 바꿀 수 있습니다.
- 선택 상자에서 코드 구문 테마 중 하나를 선택하여 치트 시트에 생성 할 수 있습니다 (선택할 수 있는 테마는 약 25 가지입니다).
누군가가 필요하면 공개 저장소에 넣겠습니다. 나는 또한 어제 이것을 시작 했으므로 아직 완벽한 치트 시트가 아닐 수도 있습니다.
또한 내 목표는 이 모든 것을 한 페이지에 맞추는 것이었지만 너무 많은 정보가 있었습니다. 누구든지 교체 / 제거 할 부품에 대한 제안이 있으면 언제든지 알려주십시오.
브라우저를 닫은 후에도 변경 사항이 유지되므로 모든 작업을 다시 수행 할 필요가 없습니다.
여기까지 치트 시트에 있는 내용의 전체 목록이 있습니다 (시간이 지남에 따라 치트 시트를 계속 업데이트 할 것입니다).
Fragments
// Does not support key attribute
const App = () => (
<>
<MyComponent />
</>
)
// Supports key attribute
const App = () => (
<React.Fragment key="abc123">
<MyComponent />
</React.Fragment>
)
Return Types
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 />,
]
Error Boundary (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>
)
Static Methods
// 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) {...}
}
Component States
// 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} />
Rendering Components
// 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} />
Default Props
// 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} />
}
}
Other React Exports
// 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)
Importing
// 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'
Pointer Events (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>
)
Synchronous / Asynchronous act Test Utility (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
})
})
결론
이것으로 이 포스트의 끝이 끝납니다! 이 정보가 도움이 되었기를 바라며 앞으로 더 많은 정보를 찾아 보시기 바랍니다.
- 이전글JSON 웹 토큰으로 Node.js 애플리케이션 보안 19.08.20
- 다음글450 개 이상의 사전 구축 된 웹 사이트 19.08.20