为什么 React 在页面底部显示我的功能组件?
Why does react display my functional component at the bottom of my page?
我的主页是这样的:
import React from "react";
import { Fragment } from "react";
import ModalA from "../components/Modal/ModalOptionA";
export default class AePage extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Fragment>
<div className="grid-intro">
<div className="text-intro">
Some Text
</div>
<div className="modal-component-insert">
<ModalA show={true}/>
</div>
<div className="text-outro">
Some text
</div>
</div>
</Fragment>
)
}
}
我的组件如下所示:
import React from "react";
import ReactDOM from "react-dom";
const Modal = ({ show, closed}) => {
return (
ReactDOM.createPortal(
<>
<div className="modal">
My Component
</div>
</>,
document.body
)
)
}
export default Modal;
上面的代码显示如下:
Some Text
Some Text
My Component
为什么我的组件不显示在文本之间? React 是否有特定的方式在我的 div 之间显示此组件?
这就是 ReactDOM.createPortal
的用途。它总是会把东西移到 DOM 的底部。这样,您就可以使用 CSS.
将其置于其他所有内容之上
看来你并不真的需要它,所以我只是将你的模态组件代码替换为:
import React from "react";
const Modal = ({ show, closed}) => {
return (
<div className="modal">
My Component
</div>
)
}
export default Modal;
我的主页是这样的:
import React from "react";
import { Fragment } from "react";
import ModalA from "../components/Modal/ModalOptionA";
export default class AePage extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Fragment>
<div className="grid-intro">
<div className="text-intro">
Some Text
</div>
<div className="modal-component-insert">
<ModalA show={true}/>
</div>
<div className="text-outro">
Some text
</div>
</div>
</Fragment>
)
}
}
我的组件如下所示:
import React from "react";
import ReactDOM from "react-dom";
const Modal = ({ show, closed}) => {
return (
ReactDOM.createPortal(
<>
<div className="modal">
My Component
</div>
</>,
document.body
)
)
}
export default Modal;
上面的代码显示如下:
Some Text
Some Text
My Component
为什么我的组件不显示在文本之间? React 是否有特定的方式在我的 div 之间显示此组件?
这就是 ReactDOM.createPortal
的用途。它总是会把东西移到 DOM 的底部。这样,您就可以使用 CSS.
看来你并不真的需要它,所以我只是将你的模态组件代码替换为:
import React from "react";
const Modal = ({ show, closed}) => {
return (
<div className="modal">
My Component
</div>
)
}
export default Modal;