[英]passing function as a prop
I have recently started a project and now I am trying to pass an onClick function as a prop of a Menubar so when I click on the image in Taskbar it displays the Menubar content我最近开始了一个项目,现在我试图传递一个 onClick 函数作为菜单栏的道具,所以当我点击任务栏中的图像时,它会显示菜单栏内容
import React from 'react'
import "./MenuBar.css"
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function MenuBar() {
const [open, setOpen] = React.useState(true);
const [close, setClose]= React.useState(false)
const TaskBar=()=>{
const [open, setOpen] = React.useState(true);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div className="taskbar">
<img onPress={() => handleOpen(true)} className="menu"
<MenuBar onPress={() => handleClose(false)}/>
I think you want to pass the function, handleOpen
, not the result of executing the function, handleOpen()
.我认为您想传递函数handleOpen
,而不是执行函数handleOpen()
。 Does this work?这行得通吗?
<img onClick={handleOpen} className="menu" />
Update更新
Based on your edited code, I think this is what you are trying to do:根据您编辑的代码,我认为这就是您要执行的操作:
import React from 'react'
import "./MenuBar.css"
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function MenuBar(props) {
return <div className='my-menu-bar-content'>
<span>MENU</span>
<p>This is some sample menu content.</p>
<button onClick={props.closeMenu}>Close</button>
</div>
}
function TaskBar(props){
const [isMenuOpen, setIsMenuOpen] = React.useState(false);
function openMenu(){
setIsMenuOpen(true)
}
function closeMenu(){
setIsMenuOpen(false)
}
return (
<div className="taskbar">
<img onClick={openMenu} className="menu" />
{isMenuOpen ? <MenuBar closeMenu={closeMenu} />: null}
</div>
)
}
In your case <img onClick={this.handleOpen()} className="menu"
will looped在你的情况下<img onClick={this.handleOpen()} className="menu"
将循环
You should pass the only function without invoke it like this -> <img onClick={this.handleOpen} className="menu"
你应该传递唯一的函数而不像这样调用它 -> <img onClick={this.handleOpen} className="menu"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.