我在我的Reactjs代码中创建了一个新组件,并在其中带有带有onClick函数的按钮。但是onClick函数不起作用。我尝试了一切,但仍然无法正常工作。有什么想法可以解决这个问题吗?
import React, { Component } from 'react';
import MenuIcon from '@material-ui/icons/Menu';
class HeaderComponent extends React.Component {
constructor(props){
super(props);
this.openMenuBar = this.openMenuBar.bind(this);
}
openMenuBar(){
console.log("open");
}
render(){
return(
<div>
<button onClick={() => { this.openMenuBar()}}>
<MenuIcon/>
</button>
</div>
);
}
}
然后在app.js中调用此组件
<HeaderComponent/>
更新
一些有益的信息:每当我将其路由到某个路径(应用程序/路径/ xx)时,该按钮均不可单击。否则,是否可以单击(如果路径为根)
答案 0 :(得分:1)
语法应为
onClick={this.openMenuBar}
或
onClick={() => { return this.openMenuBar()}}
或
onClick={() => this.openMenuBar() }
class MenuIcon extends React.Component {
render(){
return <i className="fas fa-plus" />
}
}
class HeaderComponent extends React.Component {
constructor(props){
super(props);
this.openMenuBar = this.openMenuBar.bind(this);
}
openMenuBar(){
console.log("open");
}
render(){
return(
<div>
<button onClick={this.openMenuBar}> <MenuIcon /></button>
<button onClick={() => this.openMenuBar()}> btn2</button>
<button onClick={() => { return this.openMenuBar()}}> btn3</button>
</div>
);
}
}
ReactDOM.render(<HeaderComponent />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<div id="root"></div>
答案 1 :(得分:0)
尝试
openmenubar = () => {
...
}
和
<button onClick = { () => this.openmenubar() } > </button>