【问题标题】:Fix TypeError: matchesSelector is not a function in React component修复 TypeError:matchesSelector 不是 React 组件中的函数
【发布时间】:2020-07-28 20:02:20
【问题描述】:

我正在尝试使用here 中的masonry-layout 在我的组件中创建一个砌体网格。但是,我遇到了单击组件呈现的元素返回错误TypeError: matchesSelector is not a function 的问题。我将砌体功能移至组件并将其包装在 useEffect 中,这似乎解决了其他渲染问题,但现在它说它无法在点击时触发该功能。

我在想我可能需要在网格上使用useRef,但不确定这里的实现。

我可以在fiddle 中使用纯 JS 来获得我想要的大部分功能,但尝试将其转换为 React 组件。

    import React, { useEffect } from 'react';
    import Masonry from 'masonry-layout';

    const Grid = items => {
        useEffect(() => {
        const grid = document.querySelector('.grid');
        const masonry = new Masonry(grid);
        let previouslyEnlarged;
        let matchesSelector = () => {};
        grid.addEventListener('click', function(event) {
            if (!matchesSelector(event.target, '.grid-item')) {
                return;
            }

            if (previouslyEnlarged === event.target) {
                return;
            } else if (previouslyEnlarged) {
                previouslyEnlarged.classList.remove('grid-item--gigante');
            }

            previouslyEnlarged = event.target;

            event.target.classList.toggle('grid-item--gigante');
            masonry.layout();
        });
    });
    return (
        <div>
            <div class="grid">
                <div class="grid-holder">{items.map((item, i) => <div class="grid-item">{item.name}</div>)}</div>
            </div>
        </div>
    );
};

export default Grid;

【问题讨论】:

  • 你用 let matchesSelector 声明了matchesSelector;但不会将其初始化为任何内容,因此它是未定义的。然后,当您尝试调用它时,它会给出错误,因为它是未定义的。在您的小提琴中,它看起来像是一个全局对象,因为它没有在您的代码中声明,因此请尝试删除您声明 matchSelector 的行。

标签: javascript reactjs masonry


【解决方案1】:

因此,启用对每个网格项的访问并单击它的技巧是使用挂钩来设置状态并切换类:

    const [selected, setSelected] = useState(null);
    const expandItem = e => {
        const index = parseInt(e.target.getAttribute('data-index'));
        setSelected(index);
    };

                

    <div className={`grid-item ${selected === i && 'grid-item--gigante'}`}
        onClick={expandItem}
        data-index={i}>item data</div>
        

【讨论】:

    【解决方案2】:

    let matchesSelector; 未定义。如果你想让它成为一个函数,你必须初始化它。类似:

    let matchesSelector = () =&gt; { ... };

    【讨论】:

    • 我更新了我的代码(和上面的示例),但它仍然没有触发点击时的 div。
    • 他显然是在尝试使用库方法,而不是尝试实现matchesSelector函数。
    • 我错过了什么,我能够触发对小提琴中的砖石映射的每个元素的点击,但它没有在我的反应组件中触发?
    猜你喜欢
    • 2020-08-07
    • 2020-02-09
    • 2020-08-26
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2021-11-27
    相关资源
    最近更新 更多