为什么我的 HOC 组件工作正常? #反应

why my HOC Component is working properly ? #React

2 个组件:- ClickCounter、mouseHoverCounter! 1 个 HOC 组件来做计数工作。

早些时候我通过在每个组件(cliccounter,mousehovecounter)中编写单独的计数器方法来计算点击和鼠标悬停, 但 现在,我正在尝试将组件传递到 hoc 计数器并仅进行一次更改即可获得新组件,我将道具传递给 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>

只有这个!

检查控制台中的错误, index.js:1 Warning: <originalComponent /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements. at originalComponent

这意味着您正在使用 originalComponent 中的小写字母 React 组件应该以大写字母开头

在你的 HOC 组件中试试这个

import React from 'react'

const updatedComponent = OriginalComponent => {

    class NewComponent extends React.Component {
        render(){
            return <OriginalComponent name='Harsh'/>
        }
    }
    return NewComponent
}

export default updatedComponent