0

I want to write a npm package somePackage. Now I write another codes to use this package. If the custom code write the functionA, I would use itself functionA, otherwise I will use the functionA in this package. But I failed to make the custom functionA running in the somePackage context.

class somePackage extends React.Component{
    constructor(props)
    {
        super(props);
    }

    functionA () {
        if (this.props.functionA)
            this.props.functionA.call(this);
        ...some other codes...
    }
}

class customComponent extends React.Component{
    ...
    functionA(){
        this.setState(state => ({ tags: [...this.state.tags, tag] }));
    }

    render(){
        return (<somePackage/>)
    }
}

I hope the this.props.functionA.call(this) could make the this.props.functionA running in the somePackage context, but it actually is running in the customComponent context. This this pointer is still pointing to the customComponent.

1 Answers1

1

Use the arrow function syntax instead:

    functionA = () => { // arrow function allows "this" to refer to the class when the function is called
        if (this.props.functionA)
            this.props.functionA.call(this);
        ...some other codes...
    }
Yannick K
  • 4,887
  • 3
  • 11
  • 21