简体   繁体   中英

React HOC - Access wrapped component function

PRESENTATIONAL COMPONENT
class ClientsPage extends React.Component {

_myFunction() {
//do what needs to be done
}

render() {
return <div></div>
}
}
export default doMagic(ClientsPage)



HOC COMPONENT
export const doMagic= (WrappedComponent) => {
    return class MyMagic extends React.Component {
        render() {
            const props = Object.assign({}, this.props , {
                xxx: ???,
            });

            return <WrappedComponent { ...props } />
        }
    };
}

Hi guys, i have react component and want to transform it in some way in my HOC component. But heres the problem. I want to create another prop lets call it xxx in HOC. This prop will be of type object and one of properties of this object should be function from wrapped component so womething like

xxx : {callback : reference to function from wrapped component }

Is this even possible ?

thx in advance

You can do callback to wrapped component's function with WrappedComponent.prototype._myFunction()

const doMagic= (WrappedComponent) => {
        return class MyMagic extends React.Component {
            render() {
                const props = Object.assign({}, this.props , {
                    xxx: WrappedComponent.prototype._myFunction()
                });

                return <WrappedComponent { ...props } />
            }
        };
}

class ClientsPage extends React.Component {

        _myFunction() {
            return "Wrapped Component Function Callback Done..!";
        }

        render() {
            return <div>Hello {this.props.xxx}</div>
        }
}

export default doMagic(ClientsPage)

You can see the working jsfiddle here https://jsfiddle.net/12ojjddw/

If you want to access WrappedCompoent props, then you need to use Inheritance Inversion, it is a bit more complex, but allows you full control, here is a good explanation:

https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM