🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
![](https://box.kancloud.cn/fe05b73d640ab87fea176d77edd23f10_334x135.png) 一个组件身上会有两个属性`props`和`context`,props不必多讲,context则是根组件(没有父级但有子级的组件)开辟的一块作用域,让子孙组件能够轻易的通过这个作用域拿到根组件共享出的属性和方法。 ``` static childContextTypes(根组件) --- static contextTypes(子孙组件) //通知一声要传递 / 接收 环境中的哪些方法和变量 getChildContext(){} // 具体要传递的方法和属性 ``` >**注意:** 即使是函数式组件,也会有两个属性 ## v001 ``` //index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App.js'; // import {Route} from 'react-router-dom'; import {Route} from './react-router-dom'; let Home = ()=><div>home</div>; let User = ()=><div>User</div>; let Detail = ()=><div>detail</div>; ReactDOM.render(<App> <Route path='/home' component={Home}/> <Route path='/user'component={User}/> <Route path='/detail' component={Detail}/> </App>, document.getElementById('root')); ``` // ``` //Router/HashRouter.js import React from 'react'; import PropTypes from 'prop-types'; export default class xxx extends React.Component{ static childContextTypes = { location:PropTypes.object ,history:PropTypes.object } constructor(props){ super(props); this.state = { location:{ pathname:window.location.hash.slice(1)||'/' } } } getChildContext(){ return { location:this.state.location ,history:{ push(path){ console.log(path); window.location.hash = path; //会自动添加'#' } } } } componentDidMount(){ let render = ()=>{ this.setState({location:{pathname:window.location.hash.slice(1)||'/'}}); } window.addEventListener('hashchange',render); } render(){ return this.props.children; } } ``` // ``` // Router/Route.js import React from 'react'; import PropTypes from 'prop-types'; export default class xxx extends React.Component{ static contextTypes = { location:PropTypes.object ,history:PropTypes.object } render(){ let {path,component:Component} = this.props; let {location:{pathname}} = this.context; // console.log(this.context); if(path === pathname||pathname.startsWith(path)){ return <Component location={this.context.location}/>; }else{ return null; } } } ``` // ``` // Router/Link.js import React from 'react'; import PropTypes from 'prop-types' export default class xxx extends React.Component{ static contextTypes = { history:PropTypes.object } render(){ return ( <a onClick={()=>this.context.history.push(this.props.to)}> {this.props.children} </a> ) } } ``` // ``` // Components/App.js import React from 'react'; // import {HashRouter as Router,Link} from 'react-router-dom'; import {HashRouter as Router,Link} from '../react-router-dom'; export default class xxx extends React.Component{ render(){ return ( <Router> <div className='container'> <ul className='Nav'> <li><Link to='/home'>首页</Link></li> <li><Link to='/user'>用户</Link></li> <li><Link to='/detail'>详情</Link></li> </ul> <div className='View'> {this.props.children} </div> </div> </Router> ) } } ```