在TypeScript中使用scrollTop方法时调用签名错误

时间:2017-05-16 08:59:28

标签: javascript typescript

我希望cardSummary元素在单击时滚动到顶部。这是我到目前为止应用的内容:

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

现在,当我想编译它时,我收到错误Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures.

当元素超出视口时,我该怎么做才能调用scrollTop方法?

以下是整个组件:

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

1 个答案:

答案 0 :(得分:0)

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.