0

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>

仅此而已!

4

1 回答 1

0

检查控制台中的错误, 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
于 2021-10-28T03:41:47.360 回答