关于react组件复用的总结
第一种 render props模式
将复用的逻辑代码放到一个组件中,渲染的ui界面是通过在渲染逻辑组件的时,通过传递函数的形式传入到逻辑组件中,逻辑组件在render函数中,通过this.props.children调用函数,并且传入状态
class App extends React.Component {
constructor() {
super()
}
render() {
return (<div><Son >{(son) => {
return (
<div>
<p>第二次水平:{son.x}</p>
<p>第二次水平:{son.y}</p>
</div>
)
}}</Son></div>)
}
}
class Son extends React.Component {
constructor() {
super()
this.state = {
x: 0,
y: 0
}
}
handle = (e) => {
this.setState({
x: e.screenX,
y: e.screenY
})
}
componentDidMount() {
window.addEventListener("mousemove", this.handle)
}
render() {
return this.props.children(this.state)
}
}
第二种 高阶组件的使用
高阶组件,封装一个函数来扩展组件的使用,首先这个函数必须以With开头,指定参数(参数为一个组件,大写字母开头),在函数内部创建一个类组件,提供复用的逻辑代码以及状态,在类组件中返回参数组件并且传值,在函数中导出类组件
class Partens extends React.Component {
constructor() {
super()
}
render() {
return (<div>横向:{this.props.x} 纵向:{this.props.y}</div>)
}
}
// 高阶函数(逻辑处理函数)
function WithMouse(Partens) {
class Son extends React.Component {
constructor() {
super()
this.state = {
x: 0,
y: 0
}
}
handle = (e) => {
console.log(e)
this.setState({
x: e.screenX,
y: e.screenY
})
}
componentDidMount() {
window.addEventListener("mousemove", this.handle)
}
componentWillUnmount() {
window.removeEventListener("mousemove")
}
render() {
注意在这里最好将props传递进去,不然props会丢失,只能传递到函数中类组件上
return (<Partens {...this.state} {...this.props} />)
}
设置displayName
Son.displayName = `withMouse${getDisplayName(Partens)}`
}
return Son
}
设置displayName
function getDisplayName(wrappedComponent) {
return wrappedComponent.displayName || wrappedComponent.name || "component"
}
// 最终的组件
const MousePosition = WithMouse(Partens)