05- React中的高级组件

96 阅读5分钟

一、父传子Props

  • 组件是封闭的,要接收外部数据应该通过props来实现
  • 传递数据:给组件标签添加属性
  • 接收数据:函数组件通过参数props接收数据,类组件通过this.props接收

1、函数组件

<Hello name="jack" age={19} />

function Hello(props) {
  console.log(props)
  
  return (
    <div>接收到数据:{props.name}</div>
  )
}

2、类组件

class Hello extends React.Component {
  render() {
    return (
    	<div>接收到的数据:{this.props.age}</div>
    )
  }
}

<Hello name="jack" age={19}>

特点

  1. 可以给组件传递任意类型的数据
  2. props是只读的对象,只能读取属性
  3. 注意:使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取到props
class Helllo extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return <div> 接收到数据:{this.props.age}</div>
  }
}

二、子传父Props

1、父组件提供一个回调函数

class Parent extends React.Component { 
		getChildMsg = (msg) =>{
      console.log(msg)
    }
  return () {
    return (
    	<div>子组件:<Child getMsg = {this.getChildMsg}/></div>
    )
  }
}

2、子组件通过props调用回调函数

class Child extends React.Component {
  state = {childMsg:'React'}
  handleChick = () =>{
    this.props.getMsg(this.state.childMsg)
  }
  return (
  	<button onClick={this.handleChick}>点我,给父组件传递数据</button>
  )
}

三、兄弟组件状态传值

状态提升提升到公用的父组件来进行状态管理

class Counter extends React.Component {
  state = {count: 0}
  
  // 提供修改状态的方法
  onIncrement = () => {
    this.setState({
      count: this.state.count + 1
    })
  }
  
  render() {
    return (
    	<div>
      	<Child1 count={this.state.count} />
        <Child2 onIncrement={this.onIncrement} />
      </div>
    )
  }
}

const Child1 = props => {
  return <h1>计数器:{props.count}</h1>
}
const Child2 = props => {
  return <button onClick={() => props.onIncrement()}>+1</button>
}

ReactDOM.render(<Counter />,document.getElementById('root'))

四、跨数据传值Context

1、调用React.createContext()创建Provider(提供数据)和Consumer(消费数据) 两个组件

2、使用Provider组件作为父节点。

3、设置value属性,表示要传递的数据。

4、用Consumer去接受

import { Component,createContext } from "react"
// 创建context得到两个组件
const { Provider,Consumer } = React.createContext(/**默认值*/)

class App extends React.Component {
  render() {
    return (
      <Provider value="pink">
    		<div className="app">
      		<Node />
      	</div>
      </Provider>
    )
  }
}

const Node = props => {
  return (
  	<div className="node">
    	<SubNode />
    </div>
  )
}

const SubNode = props => {
  return (
  	<div className="subnode">
    	<Child />
    </div>
  )
}

const Child = props => {
  return <div className="child"> 
  	<Consumer>
    	{data => <span>我是子节点 -- data</span>}
    </Consumer>
  </div>
}

ReactDOM.render(<App />,document.getElementById('root'))

五、children属性

1、children属性

  • children属性:表示组件标签的子节点。当组件标签有子节点时,props就会有该属性
  • children属性与图痛的props一样,值可以是任意值
function Hello(props) {
  return (
  	<div>
    			组件的子节点:{props.children}
      {/** 
     		 	等于  
      		组件的子节点:我是子节点
      */}
  	</div>
  )
}
<Hello>我是子节点</Hello>

六、props校验

1、约束规则

1、常见类型:array bool func number object string

2、React元素类型:element

3、必填项:isRequired 用法:PropTypes.array.isRequired

4、指定特定的结构对象:shape({ })

2、使用步骤

1、安装prop-typs

yarn add prop-types

2、实现

import PropTypes from 'prop-types'

function Hello(props) {
  const arr = props.colors
  const lis = arr.map(item,index) => <li key={index}>{item}</li>
  return (
  	<ul>
    			{lis}
  	</ul>
  )
}

Hello.propTypes = {
  colors:PropTypes.array
}
Hello.propTypes = {
  colors:PropTypes.array,
  filter: PropTypes.shape({
    area:PropTypes.string
    name:PropTypes.string
  })
}
<Hello 
  colors={['red','blue']} 
  filter={{name:'nihao',area:'hahha'}} >我是子节点>
</Hello>

七、props的默认值

  • 场景:分页组件 ---> 每页显示条数
  • 作用:给props设置默认值,在未传入props时生效
function App(props) {
  return (
  	<div>
    	此处展示props的默认值:{props.pageSize}
    </div>
  )
}
// 设置默认值
App.defaultProps = {
  pageSize: 10
}

// 不传pageSize属性
<App />

七、组件的生命周期

1、组件生命周期的概述

  • 意义:有助于理解组件的运行方式、完成更复杂的组件功能、分析错误

2、生命周期的三个阶段

1、创建时

创建时触发时机作用
constructor()创建组件时,最先执行1、初始化state
2、为事件处理程序绑定this
render()每次组件渲染都会触发渲染UI(不能调用setState())
componentDidMount组件挂载(完成DOM渲染)后1、发送网络请求
2、DOM操作

2、更新时

更新时触发时机作用
render每次组件渲染都会触发
componentDidUpdate(prevProps){}
preProps 上次的props参数
组件更新(完成DOM渲染)后1、发送网络请求
2、DOM操作
注意:如果要setState() 必须放在一个if条件中
子组件接受new props, setState(), forceUpdate()
就会更新

3、卸载时

钩子函数触发时机作用
componentWillUnmount组件卸载(从页面中消失)执行清理工作

八、render-props和高阶组件

1、组件复用

1、render props 模式

class Mouse extends React.Component {
  state = {
    x: 0,
    y: 0
  }
  
  // 鼠标移动事件的处理程序
  handleMouseMove=e => {
    this.setState({
      x:e.clientX,
      y:e.clientY
    })
  }
  
  // 监听鼠标移动事件
  componentDidMount() {
    window.addEventListener('mousemove' , this.handleMouseMove)
  }
  
  // 卸载移动事件
  componentWillUnmount() {
    window.removeEventListener('mousemove', this.handleMouseMove)
  }
  
  render () {
    return this.props.children(this.state)
  }
}

Mouse.propType = {
  children: propTypes.func.isRequired
}

class App extends React.Component {
  render() {
    return (
    	<div>
      	<h1>render props 模式</h1>
        <Mouse>
          {(mouse) => {
            return <p>鼠标当前位置:{mouse.x}{mouse.y}</p>
          }}
        </Mouse>
      </div>
    )
  }
}

2、高阶组件

1、概念
  • 目的:实现状态逻辑复用
  • 采用 包装(装饰)模式,比如说:手机壳

高阶组件(HOC , Higher-Order Component) 是一个函数,接收要包装的组件,返回增强后的组件

高阶组件内部创建一个类组件,在这个组件中提供复用的状态逻辑代码,通过prop将复用的状态传递给包装组件WrappedComponent

2、实现
  1. 创建一个函数,名称约定以with开头
  2. 指定函数参数,参数应该以大写字母开头(作为要渲染的组件)
  3. 在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回
  4. 在该组件中,渲染参数组件,同时将状态通过prop传递给参数组件
  5. 调用该高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,并将其渲染到页面中

// 创建高阶组件
function withMouse(WrappedComponent) {
  class Mouse extends React.Component {
    // 鼠标状态
    state = {
      x: 0,
      y: 0
    }
    
    // 鼠标移动事件的处理程序
  	handleMouseMove=e => {
    	this.setState({
      	x:e.clientX,
      	y:e.clientY
    	})
  	}
    
    // 控制鼠标状态的逻辑
    componentDidMount() {
       window.addEventListener('mousemove' , this.handleMouseMove)
  	}
  
 	 	// 卸载移动事件
    componentWillUnmount() {
       window.removeEventListener('mousemove', this.handleMouseMove)
  	}
    
    render() {
      return <WrappedComponent {...this.state}></WrappedComponent>
    }
  }
  return Mouse
}

// 用高阶组件的组件
const Position = props => (
	<p>
  	鼠标当前位置:(x:{props.x},y: {props.y})
  </p>
)

// 获取增强后的组件:
const MousePosition = withMouse(Position)

class App extends React.Component {
  render() {
    return (
    	<div>
      	<h1>高阶组件</h1>
        {/* 渲染增强后的组件 */}
        <MousePosition />
      </div>
    )
  }
}
3、高阶组件存在的问题

​ 1、 设置displayName

问题:得到两个组件名称相同都是Mouse

原因:默认情况下,React使用组件名(类名)作为displayName

解决方式:为高阶组件设置displayName

function withMouse(WrappedComponent) {
  	class Mouse extends React.Component {
      ...
    }
		Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`
}
function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComPonent.name || 'Component'
}

​ 2、传递props

问题:Props丢失

原因:高阶组件没有往下传递props

解决方式 渲染WrappedComponent时,讲state和this.props一起传递给组件

<WrappedComponent {...this.state} {...this.props}></WrappedComponent>