高阶函数(HOF)函数里面返回函数
高阶组件(HOC)函数里面返回组件

实例一

子组件1和2 有着不同的dom和延迟修改数据的时间, 通过参数(HOCfunc(1000,Child1))传递给高阶组件,以实现复用效果

  1. import React,{Component} from 'react'
  2. //子组件1
  3. function Child1 (props){
  4. return (
  5. <p>Child1-{props.n}</p>
  6. )
  7. }
  8. //子组件2
  9. function Child2 (props){
  10. return (
  11. <p>Child2-{props.n}</p>
  12. )
  13. }
  14. //高阶组件
  15. const HOCfunc = (timeout,Comp)=>{
  16. return class extends Component{
  17. state = {num:1}
  18. componentDidMount(){
  19. //延时修改数据
  20. setTimeout(() => {
  21. this.setState({
  22. num:20
  23. })
  24. }, timeout);
  25. }
  26. render(){
  27. return (
  28. <Comp n={this.state.num}></Comp>
  29. )
  30. }
  31. }
  32. }
  33. const HocChild1 = HOCfunc(1000,Child1)
  34. const HocChild2 = HOCfunc(2000,Child2)
  35. function App(){
  36. return (
  37. <div>
  38. <HocChild1></HocChild1>
  39. <HocChild2></HocChild2>
  40. </div>
  41. )
  42. }
  43. export default App;

实例二 withRouter

v6没有withRouter , 实现方法如下:

  1. hooks函数组件可以用const navigate = useNavigate()
  2. 类组件自定义withRouter

    自定义withRouter

  1. import React from 'react'
  2. import {
  3. useNavigate,
  4. useParams,
  5. useLocation
  6. }from 'react-router-dom'
  7. export default function withRouter(Component) {
  8. return function(props){
  9. const push = useNavigate()
  10. const match = useParams()
  11. const location = useLocation()
  12. //props 将组件原有的props返回 同时增加history
  13. return <Component {...props} history={{push,match,location}}/>
  14. }
  15. }

使用

import React, { Component } from 'react'
import withRouter from '../../components/withRouter'

class FilmItem extends Component {
    render() {
        return (
            <li onClick={()=>this.handleClick(this.props.filmId)}>
                {this.props.name}
            </li>
        )
    }

    handleClick(id){
        // console.log(this.props.history)
        this.props.history.push(`/detail/${id}`)

        // this.props.history.push 跳转页面
        // this.props.history.match 获取参数
        // this.props.history.location 获取当前路由
    }
}

export default withRouter(FilmItem)//****