首页 > 解决方案 > materialize.css 中的 materialboxed 不起作用

问题描述

我正在尝试使用 materialboxed 和 materialize.css 在我的反应应用程序中将我的图像作为灯箱打开,但它不起作用。人们告诉我querySelectorAll在我的中使用,useEffect但这也不起作用。这是我的代码

import React, {Fragment, useContext, useEffect} from 'react';
import {GlobalContext} from "../../context/GlobalState";
import Parallax from "../layout/Paralex";
import {Link} from "react-router-dom";
import M from 'materialize-css/dist/js/materialize.min.js';


const Pillow = ({location, match}) => {
    const {getPillow, pillow} = useContext(GlobalContext);

    useEffect(async () => {
        getPillow(match.params.id);
        const elems = await document.querySelectorAll('.materialboxed');
        M.Materialbox.init(elems)

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    if (!pillow) {
        return null
    }

    return (
        <Fragment>
            <Parallax pillow={pillow}/>
            <br/>
            <div className="row">
                <div className="col s12 m6">
                    <div className="btn white green-text waves-effect waves-red">
                        <Link to="/pillows">Back to pillows</Link>
                    </div>
                </div>
            </div>

            <div className="container">
                <div className="row">
                    {pillow.galleryImages.map(img => (
                        <div key={img.imageUrl} className="col s12 m1">
                            <img className="materialboxed responsive-img" src={img.imageUrl} alt=""/>
                        </div>
                    ))}
                </div>

请协助。谢谢 !!

标签: cssreactjsmaterialize

解决方案


为您的图像标签创建一个引用,然后在其中初始化材料箱。

const imageRef = React.useRef();

React.useEffect(() => {
   M.Materialbox.init(imageRef.current);
}, [imageRef]);

您的图片标签

<img className="materialboxed responsive-img" src={img.imageUrl} alt="" ref={imageRef}/>

它现在应该可以工作了。


推荐阅读