我有这个ParentComponent,我想要将一个名为toggleDrawer的函数传递给ChildComponent,如下所示:

const ParentComponent = () {

   const [drawerState, setDrawerState] = useState(false);

   const toggleDrawer = (anchor, open) => {
        setDrawerState(open);
   }

  return(
       <div>
         <IconButton color="primary"
                     onClick={toggleDrawer("right", true)}> // here I called to toggleDrawer so the ChildComponent can be shown
             <SomeIcon />
         </IconButton>

        <ChildComponent
             anchor="right"
             open={drawerState}
             handleDrawerState={toggleDrawer}/>

        </div>
  )
}
因此,我在toggleDrawer中获得了ChildComponent函数,如下所示:
const CartDrawer = (props) => {

 // other stuff at the top

 return(
    <Drawer
      anchor={props.anchor}
      open={props.open}
      onClose={props.handleDrawerState(props.anchor, false)}
    >
  )
}
如您所见,我通过访问handleDrawerState来获得ChildComponent中的props。但是我得到的是:

我在下面尝试过,也得到了相同的结果:
const {handleDrawerState} = props

 <Drawer
       ... other stuff
   onClose={handleDrawerState(props.anchor, false)}
>
因此,我通过console.log(props)检查浏览器中的控制台,而不是使用handleDrawerState作为密钥,在props中使用了一个对象,它的显示如下:

现在,我不明白我做错了什么,因为正如我在这里看到的那样,toggleDrawer中的ParentComponent是一个函数,但是传递给ChildComponent成为了对象。因此,我无法在propsChildComponent中访问它。
问题:
因此,将函数传递给ChildComponent的正确方法是什么?
更新:
如果我这样做:
<Drawer
    ... some other stuff
    onClose={() => props.handleDrawerState(props.anchor, false)}
>
我收到这样的错误:

最佳答案

它们需要包裹在anon函数中
如果在将函数添加为prop时将其触发,则不能将函数作为prop调用(除非您希望将触发函数的结果作为prop传递)。
应该是这个

const ParentComponent = () {

   const [drawerState, setDrawerState] = useState(false);

   const toggleDrawer = (anchor, open) => {
        setDrawerState(open);
   }

  return(
       <div>
         <IconButton color="primary"
                     onClick={() => toggleDrawer("right", true)}> //anon func here
             <SomeIcon />
         </IconButton>

        <CartDrawer
             anchor="right"
             open={drawerState}
             handleDrawerState={toggleDrawer}/>

        </div>
  )
}

const CartDrawer = (props) => {

 // other stuff at the top

 return(
    <Drawer
      anchor={props.anchor}
      open={props.open}
      onClose={() => props.handleDrawerState(props.anchor, false)} // annon func here
    />
  )
}
您现在拥有的方式在安装组件时将仅触发一次。
<MyComponent
  onClick={handleClick()} // this will always fire on mount, never do this unless you want the result from the function as a prop and not the function as itself
/>

09-10 22:27