# day__02
**Repository Path**: chb0922/day__02
## Basic Information
- **Project Name**: day__02
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2021-01-11
- **Last Updated**: 2021-01-11
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
## React 父子组件和非父子组件传值
this .props
可以接收到 外界的传值 和 此组件标签内部自定义的方法
例:
```javascript
此时在子组件中打印this.props
this.props = {
vals : '**',
sendVal : fn
}
由此我们可以进行父子组件之间传值
```
一、父传子
在子组件标签中用自定义属性进行传递,接收的时候通过this.props进行接收
```javascript
/* 父组件【自定义属性为 val 传的值为message】 */
1
2
3
/* 子组件【this.props对象中会出现 自定义属性,可以通过this.props.<属性名> 获取传值 】 */
1 render(){
2 let {val} = this.props;
3 return (
4
5 接收来自父组件的传值:{val}
6
7 )
8 }
```
二、子传父
在子组件标签内部用自定义属性定义一个方法传递给子组件 子组件调用这个方法传递参数
```javascript
/* 父组件 */
1 render(){
2 return (
3
4
5
6 )
7 }
8
9 handleRevese(params){
10 console.log('来自子组件的传值' + params);
11 }
/* 子组件 */
1 render(){
2 return (
3
4
5
6 )
7 }
8
9 handleSend(){
10 this.props.send(this.state.mess);
11 }
```
三、非父子【使用自己封装的$on $emit $off】
One组件
```javascript
1 render(){
2 return (
3
4
5
6 )
7 }
8
9 handleTwo(){
10 Observer.$emit("handle",this.state.oneVal);
11 }
Two组件
1 constructor(){
2 super();
3 this.state = {
4 oneVal:""
5 }
6 Observer.$on("handle",(val)=>{
7 this.setState({
8 oneVal:val
9 })
10 })
11 }
12
13 render(){
14 let {oneVal} = this.state;
15 return (
16 接收到one组件的值为:{oneVal}
17 )
18 }
```
## React 组件生命周期
组件的生命周期可分成三个状态:
- Mounting:已插入真实 DOM
- Updating:正在被重新渲染
- Unmounting:已移出真实 DOM
生命周期的方法有:
**componentWillMount** 在渲染前调用,在客户端也在服务端。
**componentDidMount** : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行 访问
**componentWillReceiveProps** 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
**shouldComponentUpdate** 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
**componentWillUpdate**在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
**componentDidUpdate** 在组件完成更新后立即调用。在初始化时不会被调用。
**componentWillUnmount**在组件从 DOM 中移除之前立刻被调用。
## React 实例
```javascript
以下实例在 Hello 组件加载以后,通过 componentDidMount 方法设置一个定时器,每隔100毫秒重新设置组件的透明度,并重新渲染:
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {opacity: 1.0};
}
componentDidMount() {
this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);
}
render () {
return (
Hello {this.props.name}
);
}
}
ReactDOM.render(
,
document.body
);
```
````javascript
以下实例初始化 state , setNewnumber 用于更新 state。所有生命周期在 Content 组件中。
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {data: 0};
this.setNewNumber = this.setNewNumber.bind(this);
}
setNewNumber() {
this.setState({data: this.state.data + 1})
}
render() {
return (
);
}
}
class Content extends React.Component {
componentWillMount() {
console.log('Component WILL MOUNT!')
}
componentDidMount() {
console.log('Component DID MOUNT!')
}
componentWillReceiveProps(newProps) {
console.log('Component WILL RECEIVE PROPS!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component WILL UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component DID UPDATE!')
}
componentWillUnmount() {
console.log('Component WILL UNMOUNT!')
}
render() {
return (
{this.props.myNumber}
);
}
}
ReactDOM.render(
,
document.getElementById('example')
);
````
## react 路由的几种使用方式
## React Router包含了四个包
| 包名 | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [`react-router`](https://github.com/ReactTraining/react-router/blob/master/packages/react-router) | React Router核心api |
| [`react-router-dom`](https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom) | React Router的DOM绑定,在浏览器中运行不需要额外安装`react-router` |
| [`react-router-native`](https://github.com/ReactTraining/react-router/blob/master/packages/react-router-native) | [React Native](https://facebook.github.io/react-native/) 中使用,而实际的应用中,其实不会使用这个。 |
| [`react-router-config`](https://github.com/ReactTraining/react-router/blob/master/packages/react-router-config) | 静态路由的配置 |
主要使用`react-router-dom
### 1.声明式路由
```javascript
import React, { Component } from 'react'
import { BrowserRouter as Router, Route, NavLink} from 'react-router-dom'
import './style.css'
const Home = () => 首页
const Kind = () => 分类
const Cart = () => 购物车
const User = () => 我的
export default class App extends Component {
render() {
// children --- 所有的路由都会渲染该路由对应的组件
// React路由声明式跳转 Link NavLink
return (
//渲染组件的方式
}>
{/* }> */}
)
}
}
```
### 2.编程式路由
```
@withRouter
class App extends Component {
state = {
currentIndex: 0
}
changePage = (path, index) => {
return (e) => {
this.setState({ currentIndex: index })
this.props.history.push(path)
}
}
render() {
const { currentIndex } = this.state
// 编程式跳转
return (
<>
...
>
)
}
}
```
### 3.动态路由(路由传参)
```javascript
const Child = (props) => {
console.log(props)//路由参数
const type = props.match.params.type
return (
child - { type }
)
}
class App extends Component {
render() {
return (
<>
...
>
)
}
}
```
### 4.二级路由
```javascript
import React, { Component } from 'react'
import { Route, NavLink, useRouteMatch } from 'react-router-dom'
import './style.css'
// 嵌套路由
// 分类下的 导航组件
const Phone = () => 手机
const Wash = () => 洗衣机
const Ice = () => 电冰箱
// 默认的导航组件
const Home = () => 首页
const Cart = () => 购物车
const User = () => 我的
const Kind = () => {
console.log(useRouteMatch())
const { url } = useRouteMatch() // useRouteMatch只能在函数式组件中使用
return (
)
}
class App extends Component {
render() {
return (
...
)
}
}
```
### 5.路由的重定向及精纯匹配
```javascript
import { Route, NavLink, useRouteMatch, Redirect, Switch, withRouter } from 'react-router-dom'
...
@withRouter
class App extends Component {
render() {
const pathname = '/' + this.props.location.pathname.split('/')[1]
return (
<>
...
{/* Switch 只能选择其中一个路由 */}
{/* exact 精准匹配 只有当路由为 / 时,才会重定向 */}
{/* 404路由配置在最底下 */}
>
)
}
}
```