简体   繁体   中英

Call signature error when using the scrollTop method in TypeScript

I would like the cardSummary element to scroll to top when it is clicked. This is what I've applied so far:

public onClickHandler(event: React.MouseEvent<any>): void {
    if (this.props.onClick) {
        console.log("scroll");
        if (this.isInViewport(this._cardSummary) === false) {
            this._cardSummary.scrollTop(0);
            this.props.onClick(event);
        }
    }
}

Now when I want to compile this, I get an error Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures. Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures.

What do I have to do to invoke the scrollTop method when the element is out of viewport?

Here is the component in its entirety:

export class CardSummary extends React.Component<ICardSummaryProps, undefined> {
    public static defaultProps = { labelColor: "transparent" };

    private _cardSummary: HTMLDivElement;

    public render(): JSX.Element {
        return <div className="card-summary" onClick={this.onClickHandler.bind(this)} ref={(el) => this._cardSummary = el } >
            <div>
                <div className="color" style={{ "backgroundColor": this.props.labelColor, flexShrink: 0, "float": "left" }}></div>
                <div className="row card-rowcontainer">
                    {this.props.children}
                </div>
            </div>
        </div>;
    }

    public isInViewport(element: boolean) {
        const rect = element.getBoundingClientRect();
        const html = document.documentElement;
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || html.clientHeight) &&
            rect.right <= (window.innerWidth || html.clientWidth)
        );
    }

    public onClickHandler(event: React.MouseEvent<any>): void {
        if (this.props.onClick) {
            console.log("scroll");
            if (this.isInViewport(this._cardSummary) === false) {
                this._cardSummary.scrollTop(0);
                this.props.onClick(event);
            }
        }
    }
}

Be sure you include dom types on lib inside tsconfig.json:

"target": "es5",
"lib": [
  "dom",
  "es5",
  "scripthost"
],

Note if your targe is es5 your default included libs should be don, es5 and scripthost, so, you should be well covered.

Try that, if not, please share your tsconfig.

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