react之hash值变化

import React from "react";
import PropTypes from 'prop-types'



class Router extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			hash: window.location.hash
		}
	}

	static childContextTypes = {
		hash: PropTypes.string,
	}

	getHash(){
		console.log(window.location.hash)
		let url = window.location.hash.replace('#','')
		return url
	}

	getChildContext () {
		return {
			hash: this.getHash()
		}
	}

	componentDidMount() {
		window.onhashchange = () => {
			this.setState({
				hash: this.getHash()
			})
		}
	}


	render() {
		return (
			<>
				{this.props.children}
			
		);
	}
}

class Route extends React.Component{
	static contextTypes = {
		hash: PropTypes.string
	}

	render() {
		const {
			path,
			component
		} = this.props
		let instance = null
		const {
			hash
		} = this.context
		if(path === hash) {
			instance = React.createElement(component,null,null)
		}
		return (
			<>
				{instance}
			
		);
	}
}

class AA extends React.Component{
	render() {
		return (
			
aa
); } } class BB extends React.Component{ render() { return (
bb
); } } function App() { return (
header
); } export default App

 

你可能感兴趣的:(react)