繁体   English   中英

如何使用 react 和 typescript 在反应功能组件中渲染子级?

[英]How to render children within react functional components using react and typescript?

我想使用 react 和 typescript 渲染传递给 react 功能组件的组件。

下面是我的代码,

function MainComponent () {
    return (
        <Wrapper>
            <SomeOtheComponent/>
            <DragAndDrop>
                <ListContent> //this is the children for the DragAndDrop component and want this to 
                    //render within DragAndDrop component
                    {condition_true && (
                        <FirstList/>
                    )}
                    {condition_true && (
                        <SecondList/>
                    )}
                </ListContent>
            </Wrapper>
        );
    }




const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }

     };

     const handleDragOut = (e: any) => {
         e.preventDefault();
         e.stopPropagation();
         setDragCounter((prev: number) => prev - 1);
         if (dragCounter === 0) {
             setDragging(false);
         }
     }; 

     const handleDrop = (e: any) => {
         e.preventDefault();
         e.stopPropagation();
         setDragging(false);
         if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
             e.dataTransfer.clearData();
             setDragCounter(0);
         }
     };

     return (
         <DropZone
             ref={dropRef}
             onDragEnter={handleDragIn}
             onDragLeave={handleDragOut}
             onDragOver={handleDrag}
             onDrop={handleDrop}
         >
             {dragging && <DropZoneOverlay>{children}</DropZoneOverlay>}
         </DropZone>
     );
 };

现在的问题是为什么 DragAndDrop 组件中的 ListContent 不呈现……我不确定我将子项传递给 MainComponent 中的 DragAndDrop 组件的方式是否有问题。 有人可以帮我解决这个问题。 谢谢。

DragAndDrop中的useState调用将dragging值设置为false ,因此在第一次渲染时, DropZoneOverlay不会被渲染。

{dragging && <DropZoneOverlay>{children}</DropZoneOverlay>}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM