[英]I am getting this error: “react-modal: App element is not defined”
[英]I am trying to access element inside modal(mui modal) using ref in react but reference to element is null
我正在尝试在组件中访问 did mount lifecycle 方法,但它显示 null。如果我删除模态,它会按预期工作,但模态引用内部无法正常工作。 谢谢。 我试过跟随但它总是显示 null。
import React, { Component } from "react";
import {
Modal,
Backdrop,
Fade,
Container
} from "@material-ui/core";
import { contactUsFormSchema } from "../../constant/FormValidation";
class ContactUs extends Component {
constructor(props) {
super(props);
this.state = {
};
this.rootRef = React.createRef();
this.childRef = React.createRef();
this.observer = new IntersectionObserver((entries)=>{
console.log(entries[0]);
},{
root:this.rootRef.current
});
}
componentDidMount(){
console.log(this.childRef.current); // this is always null
console.log(this.rootRef.current); // this is always null
// this.observer.observe(this.childRef.current);
}
render() {
const { classes } = this.props;
return (
<Modal
open={true}
onClose={this.props.handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500
}}
>
<Container className={classes.modalStyle} ref={this.rootRef}>
<div className={classes.title} ref={this.childRef} >Contact US</div>
</Container>
</Modal>
);
}
}
export default ContactUs;
对于那些仍然面临这个问题的人,我通过以下规则解决了它:
为模态内的内容创建子组件,然后在子组件内使用 useRef 或 createRef。
在模态中渲染子组件。
它会起作用。
示例如下(它只是一个骨架而不是一个工作件)Modal 是一个 mui 组件:
const ChildComponent = (props) => {
return (
<div ref={yourReactRef}>
<div>my content</div>
</div>
)
}
const ParentComponent = (props) => {
return (
<Modal>
<ChildComponent />
</Modal>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.