Javascript onclick处理程序在组件上不工作
在布局组件上,我有两种方法可以切换菜单打开或强制关闭。切换方法就像一个符咒,但是我希望当用户单击标题中的任何内容时菜单关闭(这样菜单就不会在页面之间保持打开状态)。然而,这部分似乎不想工作,我不知道为什么 这是我的密码:Javascript onclick处理程序在组件上不工作,javascript,reactjs,Javascript,Reactjs,在布局组件上,我有两种方法可以切换菜单打开或强制关闭。切换方法就像一个符咒,但是我希望当用户单击标题中的任何内容时菜单关闭(这样菜单就不会在页面之间保持打开状态)。然而,这部分似乎不想工作,我不知道为什么 这是我的密码: import React from 'react'; import Header from '../components/Header.jsx'; import Footer from '../components/Footer.jsx'; export default cl
import React from 'react';
import Header from '../components/Header.jsx';
import Footer from '../components/Footer.jsx';
export default class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
mobileMenuVisible: false
}
}
handleNavClick() {
// Check if the menu is visible and then toggle to the other state
if(!this.state.mobileMenuVisible) {
this.setState({mobileMenuVisible: true});
} else {
this.setState({mobileMenuVisible: false});
}
}
forceCloseNav() {
// Don't perform checks, just set the menu visibility to false
this.setState({mobileMenuVisible: false});
}
render() {
const { dispatch } = this.props;
return(
<div class={'main menu-open-'+ this.state.mobileMenuVisible} role="main">
<span class="header-toggle" onClick={this.handleNavClick.bind(this)}><div><span>Menu</span></div></span>
<Header onClick={this.forceCloseNav.bind(this)}/>
<div class="wrapper">
{ this.props.children }
</div>
<Footer />
</div>
)
}
}
从“React”导入React;
从“../components/Header.jsx”导入头文件;
从“../components/Footer.jsx”导入页脚;
导出默认类布局扩展React.Component{
建造师(道具){
超级(道具);
此.state={
移动可视性:false
}
}
handleNavClick(){
//检查菜单是否可见,然后切换到其他状态
如果(!this.state.mobileMovisible){
this.setState({mobileMenuVisible:true});
}否则{
this.setState({mobileMenuVisible:false});
}
}
forceCloseNav(){
//不执行检查,只需将菜单可见性设置为false
this.setState({mobileMenuVisible:false});
}
render(){
const{dispatch}=this.props;
返回(
菜单
{this.props.children}
)
}
}
我添加了控制台日志,可以看到组件上的onClick处理程序根本没有启动。在您的示例中,所有这些看起来都是正确的。但是,您可以检查一下,在
组件中如何处理onClick
?这是一个自定义组件,可能没有ClickHandler
下面,您可以看到一个使用html的工作示例
(按run
)
类测试扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
移动可视性:错误,
};
}
handleNavClick(){
控制台日志(“导航打开”);
this.setState({mobileMenuVisible:true});
}
强制关闭导航(事件){
event.stopPropagation();
控制台日志(“导航关闭”);
this.setState({mobileMenuVisible:false});
}
render(){
const{dispatch}=this.props;
返回(
菜单
标题内容
{this.props.children}
{this.state.mobileMovisible?'Menu Visible':'Menu Hidden'}
)
}
}
render(,document.body)代码>
啊,是的,这是一个自定义组件,因为我只想更新状态,我没有意识到我必须在该组件中添加任何内容。我已经更新了我的代码以匹配您的forceCloseNav()方法,但它似乎没有什么不同(可能是因为我的代码是自定义的),还有什么我需要做的吗?啊!我已经修复了它,我只是在header组件中添加了onClick={this.props.onClick}
。谢谢你的帮助!没错类头扩展了React.Component{render(){return嘿,这是自定义头}}`我在React上并不像我想的那样垃圾!:P非常感谢你的帮助。我认为你的答案是正确的:)