简体   繁体   English

如何在功能组件中将默认道具作为 function 传递

[英]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.

相关问题 功能组件中的默认功能道具 - Default function props in functional component 如何将函数作为道具从一个功能组件传递到另一个? - How to pass function as props from one functional component to another? 如何将道具/状态从 React Link 传递到功能组件? - How can I pass props/state from a React Link to a functional component? 反应:如何访问 class 组件中的功能组件的道具 - React: How can I acces to props of a functional component in a class component 我可以将函数传递给VueJS组件上的道具吗 - Can I Pass a Function To a Props on a VueJS Component 如何在功能组件中使用 {...this.props} - How can I use {...this.props} in a functional component 如何将具有构造函数和道具的组件转换为使用钩子和道具的功能组件 - How do I convert a component with a constructor function and props, to a functional component using hooks and props React:我可以通过prop传递组件的默认状态值吗? - React: Can I pass component default state values via props? 通过具有功能组件的道具,而无需在组件内声明功能 - pass props with functional component without declaring function within component 当父组件和子组件也是功能组件时,如何将 function 作为道具传递? - How to pass a function as props when both Parent and Child component also a functional component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM