首页 > 解决方案 > 如何使用 'this.pros.function' 调用在组件上下文中运行的函数?

问题描述

我想写一个 npm 包somePackage。现在我编写了另一个代码来使用这个包。如果自定义代码写的functionA,我会使用自己functionA,否则我会使用functionA这个包中的。但我未能使自定义functionAsomePackage上下文中运行。

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/>)
    }
}

我希望它this.props.functionA.call(this)可以this.props.functionAsomePackage上下文中运行,但它实际上是在customComponent上下文中运行的。该this指针仍然指向 customComponent。

标签: javascriptreactjs

解决方案


请改用箭头函数语法:

    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...
    }

推荐阅读