[英]How can I pass default props as function in functional component
I am using functional components in application.我在应用程序中使用功能组件。 Below is my code.
下面是我的代码。
const Modal = forwardRef((props, ref) => {
const { handleClose, children, ...rest } = props;
const [open, setOpen] = useState(false);
useImperativeHandle(ref, () => ({
handleOpen() {
setOpen(true);
},
handleClose() {
setOpen(false);
}
}));
const modalHandleClose = () => {
ref.current.handleClose();
};
return (
<Dialog
open={open}
onClose={handleClose}
scroll="body"
{...rest}
disableBackdropClick
>
{children}
</Dialog>
);
});
In above component I want pass a default prop for handleClose as below在上面的组件中,我想为 handleClose 传递一个默认道具,如下所示
Modal.defaultProps = {
handleCLose: modalHandleClose
};
but I am getting error that "modalHandleClose not defined".但我收到“未定义modalHandleClose”的错误。 What can I try to resolve this?
我可以尝试什么来解决这个问题?
React's defaultProps
can't do that, since it's a static property of the component. React 的
defaultProps
不能这样做,因为它是组件的 static 属性。 It cannot access anything that only will exist once the component renders.它无法访问只有在组件呈现后才会存在的任何内容。
I would instead recommend using default values when destructuring the props:相反,我建议在解构道具时使用默认值:
const Modal = forwardRef((props, ref) => {
const modalHandleClose = () => {
ref.current.handleClose();
};
const {
handleClose = modalHandleClose, // <----- default value
children,
...rest
} = props;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.