路由
向路由组件传递参数
params参数
路由链接(携带参数):<Link to={'/demo/test/tom/18'}>详情</Link>
注册路由(声明接收):<Route path="/demo/test/:name/:age" component={Test} />
接收参数:this.props.match.params
search参数
路由链接(携带参数):<Link to={'/demo/test?name=tom&age=18'}>详情</Link>
注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test} />
接收参数:this.props.location.search
备注:获取到的search是urlencoded编码字符串,需要借助querystring解析(import qs from 'qs')
state参数
路由链接(携带参数):<Link to={{path:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>
注册路由(无需声明,正常注册即可):<Route path="/demo/test?" component={Test} />
接收参数:this.props.location.state
备注:刷新时也可以保留住参数
编程式路由导航
借助this.props.history对象上的API对操作路由跳转、前进、后退
- this.props.history.push()
- this.props.history.replace()
- this.props.history.goBack()
- this.props.history.goForward()
- this.props.history.go()
withRouter
- 可以加工一般组件,让一般组件具备路由组件所特有的API
- 返回值是一个新组件
BrowserRouter与HashRouter的区别
底层原理不一样
- BrowserRouter使用的是H5的history API,不兼容IE9及以下版本
- HashRouter使用的是URL的哈希值
path表现形式不一样
- BrowserRouter的路径中没有#,例如:localhost:3000/demo/test
- HashRouter的路径包含#,例如:localhost:3000/#/demo/test
刷新后对路由state参数的影响
- BrowserRouter没有任何影响,因为state保存在history对象中
- HashRouter刷新后会导致路由state参数的丢失
注:HashRouter可以用于解决一些路径错误相关的问题
ant-design组件库
antd的按需引入+自定义主题
1. 安装依赖:
npm add react-app-rewired customize-cra babel-plugin-import less less-loader
2. 修改package.json
.... "scripts":{ "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }, ....
3. 根目录下创建config-overrides.js
//配置具体的修改规则 const {override, fixBabelImports,addLessLoader} = require('customize-cra'); module.exports = override( fixBabelImports('import',{ libraryName: 'antd', libraryDirectory: 'es', style: true, }), addLessLoader({ lessOptions:{ javascriptEnabled:true, modifyVars: {'@primary-color': 'green'}, } }), );
4. 备注:不用在组件里亲自引入样式了,即:import 'antd/dist/antd.css'应该删掉