1. Advanced components
Higher Order Component (HOC)
High-order components are a way for React applications to share code and increase logic reuse. For example, component A and component B both need the same logic. How do you extract the logic to A common place? The answer is to use higher-order components.
The core idea of higher-order components is to wrap another layer of executing logic components in the outer layer of components, execute logic in the outer layer of components, and then pass the result of executing logic to the inner layer of components.
Higher-order components are returned by a function that takes the component as an argument and returns a new component. The parameter component is the component that needs to reuse the logic. The new component returned by the function is the component that executes the logic. After executing the logic inside the new component, the parameter component is called and the logic result is passed to the parameter component.
Function names usually start with width, accept the component parameter name WrappedComponent, and return the same component name as the function name, except that the w in with is capitalized.
Requirement: Both components A and B need to obtain the width and height of the browser window when the browser window changes.
function withResizeable(WrappedComponent) {
function WithResizeable(props) {
const [sizes, setSizes] = useState([window.innerWidth, window.innerHeight])
useEffect(() = > {
window.addEventListener("resize".() = > {
setSizes([window.innerWidth, window.innerHeight])
})
}, [])
return <WrappedComponent sizes={sizes} {. props} / >
}
return WithResizeable
}
Copy the code
function App({ sizes, name }) {
return (
<div>
{JSON.stringify(sizes)} {name}
</div>)}export default withResizeable(App)
Copy the code
ReactDOM.render(<App name="Zhang" />.document.getElementById("root"))
Copy the code
2. Render properties
import React, { useEffect, useState } from "react"
function Resizeable({ render }) {
const [sizes, setSizes] = useState([window.innerWidth, window.innerHeight])
useEffect(() = > {
window.addEventListener("resize".() = > {
setSizes([window.innerWidth, window.innerHeight])
})
}, [])
return render(sizes)
}
export default Resizeable
Copy the code
import React from "react"
function App({ sizes }) {
return <div>{JSON.stringify(sizes)}</div>
}
export default App
Copy the code
import React from "react"
import ReactDOM from "react-dom"
import Resizeable from "Resizeable"
import App from "./App"
ReactDOM.render(
<Resizeable render={sizes= > <App sizes={sizes} />} / >.document.getElementById("root"))Copy the code