反应:显示模态时不能给功能组件提供参考 [英] React: Function components cannot be given refs when displaying a modal

查看:49
本文介绍了反应:显示模态时不能给功能组件提供参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模态在App.js中的hashRouter下呈现.当其状态为isOpen为true时,将显示模态.

当我尝试显示带有React Redux的Modal时出现此错误.

 警告:不能为功能组件提供引用.尝试访问此引用将失败.您是要使用React.forwardRef()吗?检查`TrapFocus`的渲染方法.在ConnectFunction中(在Modal.js:41)在TrapFocus中(由ForwardRef(Modal)创建)在div中(由ForwardRef(Modal)创建)在ForwardRef(Portal)中(由ForwardRef(Modal)创建)在ForwardRef(Modal)中(在Modal.js:35)在Modal中(由ConnectFunction创建)在ConnectFunction中(由WithStyles创建(未定义))在WithStyles中(未定义)(在App.js:46处)在ThemeProvider中(在App.js:24)在App中(由WithStyles(App)创建)在WithStyles(App)中(在src/index.js:13处)在提供程序中(在src/index.js:12处) 

这是我的代码:

Modal.js

  import React,{组件}来自"react";从"redux"导入{compose};从"prop-types"导入PropTypes;从"react-redux"导入{connect};从"@ material-ui/core"导入{Modal为MaterialModal};从"@ material-ui/styles"导入{withStyles};从"../store/actions/actions-ui"中导入{closeModal};从"./Modals/BasicModal"导入BasicModal;const ModalTypes = {BasicModal,};const styles = {方式:{显示:"flex",justifyContent:中心",alignItems:居中",},};类Modal扩展了Component {handleCloseModal =()=>{const {dispatch,shouldCloseOnBackgroundTouch} = this.props;如果(shouldCloseOnBackgroundTouch)dispatch(closeModal());};使成为() {const {modalType,data,isOpen,classes} = this.props;如果(!modalType){返回null;}const ModalToRender = ModalTypes [modalType];返回 (<材料模态disableAutoFocusclassName = {classes.modal}打开= {isOpen}onClose = {this.handleCloseModal}>< ModalToRender {... data}/></MaterialModal>);}}Modal.propTypes = {调度:PropTypes.func.isRequired,isOpen:PropTypes.bool.isRequired,modalType:PropTypes.string,//eslint-disable-next-line react/forbid-prop-types数据:PropTypes.object,shouldCloseOnBackgroundTouch:PropTypes.bool.isRequired,类别:PropTypes.objectOf(PropTypes.string).isRequired,};Modal.defaultProps = {数据: {},modalType:",};const mapStateToProps =(状态)=>({isOpen:state.ui.modalState.isOpen,shouldCloseOnBackgroundTouch:state.ui.modalState.shouldCloseOnBackgroundTouch,modalType:state.ui.modalState.modalType,数据:state.ui.modalState.data,});导出默认的compose(withStyles(styles),连接(mapStateToProps))(模态); 

BasicModal.js

  import React,{组件}来自"react";从"react-redux"导入{connect};从"prop-types"导入PropTypes;从"@ material-ui/core/Button"导入Button;从"@ material-ui/core/Typography"导入字体;从"@ material-ui/core/Paper"导入纸张;从"../__helpers__/If"中导入If;从"../../store/actions/actions-ui"导入{closeModal};BasicModal类扩展了Component {handleClose =()=>{const { dispatch } = this.props;dispatch(closeModal());};使成为() {const {title,text,extraBtnText,extraBtnAction} = this.props;返回 (<纸张>< Iftruey = {title}>< Typography gutterBottom variant ="h4">{标题}</Typography></If>< Iftruey = {text}><版式装订线底部vairant ="body2">{文本}</Typography></If>< Button onClick = {this.handleClose}>关闭</Button><If truthy={extraBtnAction &&extraBtnText}><按钮onClick = {()=>{extraBtnAction();this.handleClose();}}>{extraBtnText}</按钮></If></Paper>);}}BasicModal.propTypes = {调度:PropTypes.func.isRequired,标题:PropTypes.string.isRequired,文字:PropTypes.string.isRequired,extraBtnText:PropTypes.string,extraBtnAction:PropTypes.func,};导出默认的connect()(BasicModal); 

我猜测问题出在我身上,试图渲染这样的组件:

 < ModalToRender {... data}/> 

但是我似乎不明白这是怎么回事.

感谢您的帮助!

解决方案

您需要使用 Modal 包装的组件(例如, BasicModal ),在connect()中的noreferrer> forwardRef选项.

示例:

 导出默认连接(null,null,null,{forwardRef:true})(BasicModal); 

参考提供对React元素的DOM节点的访问.Material-UI的 TrapFocus (由 Modal 使用) forwardRef包裹.

connect forwardRef 选项使它使用 React.forwardRef 包装功能组件,以便它可以成功接受它所引用的ref.传递到包装的组件(在您的情况下为 BasicModal ).

The modal is rendered under the hashRouter in App.js. The modal is shown when its state isOpen is true.

I'm given this error when trying to display a Modal with react redux.

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `TrapFocus`.
    in ConnectFunction (at Modal.js:41)
    in TrapFocus (created by ForwardRef(Modal))
    in div (created by ForwardRef(Modal))
    in ForwardRef(Portal) (created by ForwardRef(Modal))
    in ForwardRef(Modal) (at Modal.js:35)
    in Modal (created by ConnectFunction)
    in ConnectFunction (created by WithStyles(undefined))
    in WithStyles(undefined) (at App.js:46)
    in ThemeProvider (at App.js:24)
    in App (created by WithStyles(App))
    in WithStyles(App) (at src/index.js:13)
    in Provider (at src/index.js:12)

This is my code:

Modal.js

import React, { Component } from "react";
import { compose } from "redux";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { Modal as MaterialModal } from "@material-ui/core";
import { withStyles } from "@material-ui/styles";
import { closeModal } from "../store/actions/actions-ui";
import BasicModal from "./Modals/BasicModal";

const ModalTypes = {
    BasicModal,
};

const styles = {
    modal: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
    },
};

class Modal extends Component {
    handleCloseModal = () => {
        const { dispatch, shouldCloseOnBackgroundTouch } = this.props;
        if (shouldCloseOnBackgroundTouch) dispatch(closeModal());
    };

    render() {
        const { modalType, data, isOpen, classes } = this.props;
        if (!modalType) {
            return null;
        }
        const ModalToRender = ModalTypes[modalType];
        return (
            <MaterialModal
                disableAutoFocus
                className={classes.modal}
                open={isOpen}
                onClose={this.handleCloseModal}
            >
                <ModalToRender {...data} />
            </MaterialModal>
        );
    }
}

Modal.propTypes = {
    dispatch: PropTypes.func.isRequired,
    isOpen: PropTypes.bool.isRequired,
    modalType: PropTypes.string,
    // eslint-disable-next-line react/forbid-prop-types
    data: PropTypes.object,
    shouldCloseOnBackgroundTouch: PropTypes.bool.isRequired,
    classes: PropTypes.objectOf(PropTypes.string).isRequired,
};

Modal.defaultProps = {
    data: {},
    modalType: "",
};

const mapStateToProps = (state) => ({
    isOpen: state.ui.modalState.isOpen,
    shouldCloseOnBackgroundTouch: state.ui.modalState.shouldCloseOnBackgroundTouch,
    modalType: state.ui.modalState.modalType,
    data: state.ui.modalState.data,
});

export default compose(
    withStyles(styles),
    connect(mapStateToProps)
)(Modal);

BasicModal.js

import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import Paper from "@material-ui/core/Paper";
import If from "../__helpers__/If";
import { closeModal } from "../../store/actions/actions-ui";

class BasicModal extends Component {
    handleClose = () => {
        const { dispatch } = this.props;
        dispatch(closeModal());
    };

    render() {
        const { title, text, extraBtnText, extraBtnAction } = this.props;
        return (
            <Paper>
                <If truthy={title}>
                    <Typography gutterBottom variant="h4">
                        {title}
                    </Typography>
                </If>
                <If truthy={text}>
                    <Typography gutterBottom vairant="body2">
                        {text}
                    </Typography>
                </If>

                <Button onClick={this.handleClose}>Close</Button>
                <If truthy={extraBtnAction && extraBtnText}>
                    <Button
                        onClick={() => {
                            extraBtnAction();
                            this.handleClose();
                        }}
                    >
                        {extraBtnText}
                    </Button>
                </If>
            </Paper>
        );
    }
}

BasicModal.propTypes = {
    dispatch: PropTypes.func.isRequired,
    title: PropTypes.string.isRequired,
    text: PropTypes.string.isRequired,
    extraBtnText: PropTypes.string,
    extraBtnAction: PropTypes.func,
};

export default connect()(BasicModal);

I'm guessing that the issue lies with me trying to render a component like this:

<ModalToRender {...data} />

But I can't seem to understand what is wrong with it.

Any help is appreciated!

解决方案

You need to use the forwardRef option in connect() for the component (e.g. BasicModal) that is wrapped by Material-UI's Modal.

Example:

export default connect(null, null, null, {forwardRef: true})(BasicModal);

Refs provide access to the DOM node for a React element. Material-UI's TrapFocus (which is used by Modal) uses a ref on the child passed to Modal to manage focus aspects.

In your case, the child passed to Modal is the wrapper component returned by connect()(BasicModal). That wrapper component is, by default, a function component and function components cannot accept refs except by being wrapped by forwardRef.

The forwardRef option of connect causes it to wrap the function component using React.forwardRef so that it can successfully accept a ref which it passes along to the wrapped component (BasicModal in your case).

这篇关于反应:显示模态时不能给功能组件提供参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆