如何将状态属性设置为false

bro*_*lyt 1 javascript reactjs gatsby

我正在检查用户是否在小于768像素的设备上,如果我要将isTop设置为false。我遇到了一些问题。一切看起来都还不错,但我不断收到此错误消息:

TypeError:_this2.state.isTop不是函数

我正在使用的是:

componentDidMount() {
    this.updateWindowDimensions();
    window.addEventListener('resize', this.updateWindowDimensions);
    document.addEventListener('scroll', () => {
        const isTop = window.scrollY < window.innerHeight - 50;
        if (isTop !== this.state.isTop) {
          this.setState({ isTop })
        }
    });

    this.checkWidth = () => {
        const match = window.matchMedia(`(max-width: 768px)`);
        if (match) {
            this.state.isTop(false);
        }
    };

    this.checkWidth();
    window.addEventListener('resize', this.checkWidth);
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

nas*_*h11 5

您的语法似乎不正确,无法将isTop状态设置为false。(来源:docs

试试这个

this.setState({isTop: false});
Run Code Online (Sandbox Code Playgroud)