![](/img/trans.png)
[英]How can i pass render props to children in React functional components?
[英]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.