微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在我的 React 组件中获取 react-modal 的错误

如何解决在我的 React 组件中获取 react-modal 的错误

抱歉,React 开发新手。我正在尝试基于示例 here 在我的 React 组件中使用 react-modal。我遇到了一些我无法弄清楚的错误

import React,{useState} from 'react';
import {
  Card,Button,CardImg,CardTitle,CardText,CardGroup,CardSubtitle,CardBody,CardFooter,CardHeader,CardColumns,CardDeck
} from 'reactstrap';
import Config from 'config';
import parse from 'html-react-parser';
import "./Item.css";
import ReactDOM from 'react-dom';
import Modal from 'react-modal';

const customStyles = {
    content: {
        top: '50%',left: '50%',right: 'auto',bottom: 'auto',marginRight: '-50%',transform: 'translate(-50%,-50%)',},};

//Modal.setAppElement('FeaturedCards');

class FeaturedCards extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'React',apiData: [],};
    }

    async componentDidMount() {
        const tokenString = sessionStorage.getItem("token");
        const token = JSON.parse(tokenString);

        let headers = new Headers({
            "Accept": "application/json","Content-Type": "application/json",'Authorization': 'Bearer ' + token.token
        });

        const response = await fetch(Config.apiUrl + `/api/Items/GetFeaturedItems`,{
            method: "GET",headers: headers
        });
        const json = await response.json();
        console.log(json);
        this.setState({ itemList: json });
    }

    render() {
        const [modalisOpen,setIsOpen] = useState(false);
        const items = this.state.itemList;
        let subtitle;
        

        function handleClick(item) {
            console.log('this is:',item);
            setIsOpen(true);
        }

        function afterOpenModal() {
            // references are Now sync'd and can be accessed.
            subtitle.style.color = '#f00';
        }

        function closeModal() {
            setIsOpen(false);
        }

        var formatter = new Intl.NumberFormat('en-US',{
            style: 'currency',currency: 'USD'            
        });

        return (
            <div>
                <CardColumns>
                    {items && items.map(item =>
                        <>
                            <Card key={item.itemNumber} tag="a" onClick={() => handleClick(item)} style={{ cursor: "pointer" }}>
                                <CardHeader tag="h3">Featured</CardHeader>
                                <CardImg top className="card-picture" src={"data:image/png;base64," + item.images[0]?.ImageData)} id={item.itemNumber + "Img"} alt={item.itemNumber} />
                                <CardBody className="card-body">
                                    <CardTitle tag="h5">{item.itemNumber}</CardTitle>
                                    <CardSubtitle tag="h6" className="mb-2 text-muted">{item.categoryName}</CardSubtitle>
                                    <CardText className="card-description">{item.itemDescription}</CardText>
                                </CardBody>
                                <CardFooter className="text-muted">{formatter.format(item.price)}</CardFooter>
                            </Card>
                            <Modal
                                isOpen={modalisOpen}
                                onAfterOpen={afterOpenModal}
                                onRequestClose={closeModal}
                                style={customStyles}
                                contentLabel="Example Modal">
                                    <h2 ref={(_subtitle) => (subtitle = _subtitle)}>Hello</h2>
                                    <button onClick={closeModal}>close</button>
                                    <div>I am a modal</div>
                                    <form>
                                        <input />
                                        <button>tab navigation</button>
                                        <button>stays</button>
                                        <button>inside</button>
                                        <button>the modal</button>
                                    </form>
                            </Modal>
                        </>
                    )}                
                </CardColumns>
            </div>
        );
    }
}
export default FeaturedCards;

我收到了一些错误

  1. 我应该把 const [modalisOpen,setIsOpen] = useState(false) 放在哪里,这样我就不会收到 Error: Invalid hook call.
  2. 我需要在 Modal.setAppElement('FeaturedCards') 中放入什么,因为 FeaturedCards 不起作用?

任何帮助将不胜感激。

解决方法

关注@Nick 和@DaveNewton 的评论后...

...
Modal.setAppElement('#root');
...

class FeaturedCards extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'React',apiData: [],isOpen: false            
        };
    }

    ...    

    render() {
        const items = this.state.itemList;
        let subtitle;
        
        // This binding is necessary to make `this` work in the callback    
        handleClick = handleClick.bind(this);
        closeModal = closeModal.bind(this);

        function handleClick() {
            this.setState({ isOpen: true });
        }

        function closeModal() {
            console.log('Clicked close button')
            this.setState({ isOpen: false });
        }

        function afterOpenModal() {
            // references are now sync'd and can be accessed.
            subtitle.style.color = '#f00';
        }

        ...

        return (
            <div>
                <CardColumns>
                    {items && items.map(item =>
                        <>
                            <Card key={item.itemNumber} tag="a" onClick={() => handleClick()} style={{ cursor: "pointer" }}>
                                <CardHeader tag="h3">Featured</CardHeader>
                                <CardImg top className="card-picture" src={"data:image/png;base64," + item.images[0]?.ImageData} id={item.itemNumber + "Img"} alt={item.itemNumber} />
                                <CardBody className="card-body">
                                    <CardTitle tag="h5">{item.itemNumber}</CardTitle>
                                    <CardSubtitle tag="h6" className="mb-2 text-muted">{item.categoryName}</CardSubtitle>
                                    <CardText className="card-description">{item.itemDescription}</CardText>
                                </CardBody>
                                <CardFooter className="text-muted">{formatter.format(item.price)}</CardFooter>
                            </Card>
                            <Modal
                                isOpen={this.state.isOpen}
                                onAfterOpen={afterOpenModal}
                                onRequestClose={() => closeModal()}
                                style={customStyles}
                                contentLabel="Example Modal">
                                    <h2 ref={(_subtitle) => (subtitle = _subtitle)}>Hello</h2>
                                <button onClick={() => closeModal()}>close</button>
                                    <div>I am a modal</div>
                                    <form>
                                        <input />
                                        <button>tab navigation</button>
                                        <button>stays</button>
                                        <button>inside</button>
                                        <button>the modal</button>
                                    </form>
                            </Modal>
                        </>
                    )}                
                </CardColumns>
            </div>
        );
    }
}
export default FeaturedCards;

...我可以打开和关闭模态。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。