React - 模拟路由实现

import React, { Component } from 'react'
import ReactDOM from 'react-dom/client'
import { nanoid } from 'nanoid'

const root = ReactDOM.createRoot(document.getElementById('root'))

class MyApp01 extends React.Component {
  // 声明状态保存url
  state = {
    url: '',
  }

  // 监听浏览器中URL的变化,将URL同步到state中
  componentDidMount() {
    const url = window.location.hash.slice(1)
    this.setState({
      url,
    })

    window.addEventListener('hashchange', () => {
      console.log(window.location.hash)
      const url = window.location.hash.slice(1)
      console.log('url: ', url)
      this.setState({ url })
    })
  }

  render() {
    const { url } = this.state
    return (
      <>
        <div>
          <h1>App组件</h1>
          <ul>
            <li>
              <a href="#/home">首页</a>
            </li>
            <li>
              <a href="#/my">我的音乐</a>
            </li>
            <li>
              <a href="#/friend">我的朋友</a>
            </li>
          </ul>
          {url === '/home' && <Home />}
          {url === '/my' && <MyMusic />}
          {url === '/friend' && <Friend />}
        </div>
      </>
    )
  }
}

function Home() {
  return (
    <>
      <div>
        <h1>首页组件</h1>
      </div>
    </>
  )
}

function MyMusic() {
  return (
    <>
      <div>
        <h1>音乐组件</h1>
      </div>
    </>
  )
}

function Friend() {
  return (
    <>
      <div>
        <h1>朋友组件</h1>
      </div>
    </>
  )
}

const divNode = (
  <div>
    <MyApp01 />
  </div>
)
root.render(divNode)

posted @ 2023-03-22 14:58  Felix_Openmind  阅读(35)  评论(0)    收藏  举报
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}