React:组件的复用
1. render -props
参考代码:
import React from 'react';
import ReactDOM from 'react-dom/client';
import PropTypes from 'prop-types'
class App extends React.Component{
render(){
return (
<div>
<Mouse render={
(mouse)=>{
// props render模式
return <p>鼠标位置:{mouse.x},{mouse.y}</p>
}
}/>
<Mouse2>
{
(mouse)=>{
// children
return <p>鼠标位置2:{mouse.x},{mouse.y}</p>
}
}
</Mouse2>
</div>
)
}
}
class Mouse extends React.Component{
state = {
x:0,
y:0
}
handlerMouse = (e)=>{
this.setState({
x:e.clientX,
y:e.clientY
})
}
componentDidMount(){
window.addEventListener('mousemove',this.handlerMouse)
}
// 完成dom渲染之后
// 卸载阶段
componentWillUnmount(){
window.removeEventListener('mousemove',this.handlerMouse)
}
render(){
return this.props.render(this.state)
}
}
class Mouse2 extends React.Component {
state = {
x: 0,
y: 0
}
handlerMouse = (e) => {
this.setState({
x: e.clientX,
y: e.clientY
})
}
componentDidMount() {
window.addEventListener('mousemove', this.handlerMouse)
}
// 卸载阶段
componentWillUnmount() {
window.removeEventListener('mousemove', this.handlerMouse)
}
render() {
return this.props.children(this.state)
}
}
Mouse2.propTypes = {
children:PropTypes.func.isRequired
}
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App/>);
2.高阶组件
参考代码:
import React from 'react';
import ReactDOM from 'react-dom/client';
function withMouse(WrappedComponent){
class Mouse extends React.Component{
state = {
x:0,
y:0
}
handleMouse = (e)=>{
this.setState({
x:e.clientX,
y:e.clientY
})
}
componentDidMount(){
window.addEventListener('mousemove',this.handleMouse)
}
render() {
return <WrappedComponent {...this.state} {...this.props}/>
// 传递 this.state this.props
}
}
Mouse.displayName = `withMouse${getDisplayName(WrappedComponent)}`
// 用于设置 调式 组件重名情况
return Mouse
}
function getDisplayName(WrappedComponent){
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}
function PositionMouse(props){
console.log(props);
return (
<p>鼠标位置:{props.x} ,{props.y}</p>
)
}
const Dv = withMouse(PositionMouse)
const App = (
<div>
<Dv name='liuze'/>
</div>
)
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(App);
运行结果: