组件复用
Render Props
分享一个组件的state到其他需要相同state的组件。
实例
跟踪并显示在页面上鼠标点击的位置,然后在点击的位置显示一张图片。
这里封装了两个组件:Mouse组件用来完成跟踪并显示鼠标的位置;Cat组件用来显示鼠标点击位置的图片。Mouse组件通过render这个方法属性来动态渲染Cat组件,这样Cat组件内部就可以使用Mouse组件的state。
render prop是一个用于告知组件需要渲染什么内容的函数prop。
import React from 'react';
import Cat from './Cat';
import Mouse from './Mouse';
function Example(){
return (
<div style={{ height: '500px' }}>
<h1>点击鼠标!</h1>
<Mouse render={(position) => <Cat position= {position}/>}/>
</div>
);
}
export default Example;
import React, { useState } from 'react';
function Mouse(props){
const [position, setPosition] = useState({ x: 0, y: 0 });
const mouseMove = (event) => {
setPosition({
x: event.clientX,
y: event.clientY
});
};
const children = props.render(position);
return (
<div style={{ height: '500px' }} onClick={mouseMove}>
<h1>鼠标的位置是 ({position.x}, {position.y})</h1>
{children}
</div>
);
}
export default Mouse;
function Cat(props){
const { position } = props;
let imgUrl = require('@/assets/images/login-logo.png');
return <img src={imgUrl} style={{ position: 'absolute', left: position.x, top: position.y }} />;
}
export default Cat;
Higher-order Components(高阶组件)
高阶组件(HOC, higher order components)是React中对组件逻辑进行重用的高级技术,本身并不是React API,只是一种模式。
高阶组件是一个函数,该函数接受一个组件作为参数,并返回一个新的组件。
const EnhancedComponent = higerOrderComponent(WrappedComponent);
高阶组件的精华是抽象出一个模式,该模式允许我们在一个地方定义逻辑,并能对所有组件只用。
实例
import { Component } from 'react';
export function hocComponent(WrappedComponent) {
return class extends Component {
render() {
return (<div>
<div className="title">{this.props.title}</div>
<WrappedComponent {...this.props} />
</div>);
}
};
}
新建Example.js组件中使用高阶组件,返回新的组件
import { hocComponent } from './hocComponent';
import Component from './Component';
export default function Example() {
return hocComponent(Component);
}
调用Example组件
<Example title="test"/>
应用
- react-redux中的connect方法
const ConnectedComment = connect(commentSelector, commentActions)(CommentList);
//可拆分成
// connect 是一个函数,它的返回值为另外一个函数。
const enhance = connect(commentListSelector, commentListActions);
// 返回值为 HOC,它会返回已经连接 Redux store 的组件
const ConnectedComment = enhance(CommentList);
- react-router中的withRouter
const withRouter = ( Component ) => () => <Route component={ Component }/>