2个组件:- ClickCounter,mouseHoverCounter!1 HOC 组件来做计数工作。
早些时候,我通过在每个组件(cliccounter,mousehovecounter)中编写单独的计数器方法来计算单击和鼠标悬停,但是现在,我试图将组件传递到 hoc 计数器并仅通过一次更改来获取新组件,其中我m 将道具传递给 originalComponent 并返回它以查看行为,但它现在正在工作......
import React, { Component } from 'react'
import updatedComponent from './hocCounter'
class ClickCounter extends Component {
constructor(props) {
super(props)
this.state = {
counter:0
}
}
ClickCounterHandler = () =>{
this.setState((prevState)=>{
return {counter:prevState.counter+1}
})
}
render() {
const count=this.state.counter
return (
<div>
<button onClick={this.ClickCounterHandler}>{this.props.name} Clicked {count} Times</button>
</div>
)
}
}
export default updatedComponent(ClickCounter)
import React, { Component } from 'react'
import updatedComponent from './hocCounter'
class HoverMouseCounter extends Component {
constructor(props) {
super(props)
this.state = {
counter:0
}
}
MouseOverCounter(){
this.setState((prevState)=>{
return {counter:prevState.counter+1}
})
}
render() {
const count=this.state.counter
return (
<div>
<h1 onMouseOver={this.MouseOverCounter.bind(this)}>{this.props.name} Hovered For {count} Time(s)</h1>
</div>
)
}
}
export default updatedComponent(HoverMouseCounter)
import React from 'react'
const updatedComponent = originalComponent => {
class newComponent extends React.Component {
render(){
return <originalComponent name='Harsh'/>
}
}
return newComponent
}
export default updatedComponent
在 App.js 中,我正在返回
<ClickCounter></ClickCounter>
<HoverMouseCounter></HoverMouseCounter>
仅此而已!