React组件复用
render props 模式
思路:将要复用的 state 和操作 state 的方法封装到一个组件中
使用步骤:
创建复用组件
将要复用的数据、方法作为 props.render(state) 方法的参数,暴露到组件外
使用 props.render() 的返回值作为要渲染的内容
- ```javascript
- import propTypes from 'prop-types'
- // 要复用的组件
- class Mouse extends React.Component {
- state = {
- x : 0,
- y : 0
- }
-
- handleMove = e => {
- this.setState({
- x : e.clientX,
- y : e.clientY
- })
- }
-
- // 监听鼠标移动事件
- componentDidMount() {
- window.addEventListener('mousemove',this.handleMove)
- }
- // 卸载鼠标移动事件
- componentWillUnmount() {
- window.removeEventListener('mousemove', this.handleMove)
- }
-
- // 将数据作为参数返回
- render() {
- return this.props.render(this.state)
- }
- }
-
- //添加Props校验
- Mouse.propTypes = {
- children : propTypes.func.isRequired
- }
-
- class App extends React.Component{
- render() {
- return (
- // 获取到参数 用返回值进行使用
- <Mouse render={(mouse) => {
- return
- 鼠标当前位置:{mouse.x},{mouse.y}
-
- }} />
- )
- }
- }
- ```
高阶组件(HOC)
简单来说:高阶组件就是提供一些数据方法,然后将普通组件套到高阶组件中,普通组件就有高阶组件中定义的那些方法和数据了
使用步骤:
创建一个函数,名称以 with 开头
指定函数参数,参数以大写字母开头(表示要渲染的组件)
在函数内部创建一个类组件,提供要复用的逻辑代码,并返回
在该组件中,渲染参数组件,同时将状态传递通过props 传递给参数组件
调用该高阶组件,传入需要增强的组件,通过返回值拿到增强后的组件,并将其渲染到页面上
需要设置 displayName,方便后期调试(不设置的话,使用这个高阶组件的所有组件显示在调试工具上的组件名都是一样的)
- ```javascript
- // 高阶组件
- 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 出去 带上数据
- return <WrappedComponent {...this.state}{...this.props} />
-
- }
- }
- // 设置 displayName作为组件名称
- Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`
- return Mouse
- }
-
- // 获取组件名称
- function getDisplayName(WrappedComponent) {
- return WrappedComponent.displayName || WrappedComponent.name || 'Component';
- }
-
- // 需要增强的组件
- const Position = props => (
- <p>
- 鼠标当前位置:x : {props.x}, y : {props.y}
- </p>
- )
-
- // 获取到增强后的组件
- const MousePosition = withMouse(Position)
-
- class App extends React.Component{
- render() {
- return (
- <div>
- <MousePosition />
- </div>
- )
- }
- }
-
- const container = document.getElementById('root')
- const root = createRoot(container)
- root.render(<App />)
- ```