我有这个 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>
)
}
所以我在 ChildComponent
中得到了 toggleDrawer
函数,如下所示:
const CartDrawer = (props) => {
// other stuff at the top
return(
<Drawer
anchor={props.anchor}
open={props.open}
onClose={props.handleDrawerState(props.anchor, false)}
>
)
}
如您所见,我通过访问 props
在 ChildComponent
中获取了 handleDrawerState
。但我得到的是:
TypeError: props.handleDrawerState is not a function
我在下面试过,也得到了同样的结果:
const {handleDrawerState} = props
<Drawer
... other stuff
onClose={handleDrawerState(props.anchor, false)}
>
所以我通过 console.log(props)
在浏览器中检查控制台,而不是使用 handleDrawerState
键,我在 props< 中有一个对象
,它像这样呈现:
proto: Object
现在,我不明白我做错了什么,因为正如我在这里看到的,ParentComponent
中的 toggleDrawer
是一个函数,但传递给了 ChildComponent
它成为对象。因此我无法在 ChildComponent
的 props
中访问它。
问题:
因此,将函数传递给 ChildComponent
的正确方法是什么?
更新:
如果我这样做:
<Drawer
... some other stuff
onClose={() => props.handleDrawerState(props.anchor, false)}
>
我得到这样的错误:
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
最佳答案
它们需要被包裹在匿名函数中
如果在将函数添加为 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
/>
关于javascript - 当父组件和子组件都是函数组件时,如何将函数作为 Prop 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63424902/