我在 React 应用程序中使用 Next JS,但在门户中创建模态时遇到问题,它抛出错误“目标容器不是 DOM 元素”。,这是我的代码。
import React, { useEffect } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import classes from './listModal.scss';
const EditorListModal = (props) => {
let container;
if (typeof window !== 'undefined') {
const rootContainer = document.createElement('div');
const parentElem = document.querySelector('#__next');
parentElem.appendChild(rootContainer);
container = rootContainer;
}
const isShown = props.show ? classes['editor-listModal--open'] : '';
const element = (
<div className={`${classes['editor-listModal']} ${isShown}`}>
// Modal Content
</div>
);
return ReactDOM.createPortal(element, container);
};
EditorListModal.propTypes …
Run Code Online (Sandbox Code Playgroud) 我有一个关于 React 函数式组件的问题,特别是关于函数式组件中的函数。例如:
import React, { useEffect } from 'react';
const Component = (props) => {
useEffect(() => {
window.addEventListener('scroll', handleScroll);
});
useEffect(() => {
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
function handleScroll() {
let scrollTop = window.scrollY;
}
return ()
}
Run Code Online (Sandbox Code Playgroud)