带有onclick的按钮在Reaction中只工作一次
我需要在Reaction应用程序中创建折叠菜单,但onclick的按钮只起作用一次。我创建了一个布尔变量,当我点击按钮时,它应该会更改。但我只能点击该按钮一次,此后<a>
不起作用,它处于非活动状态:
let isOpened = false;
class Header extends React.Component {
handleClick = () => {
isOpened = !isOpened;
};
render() {
const path = history.location && history.location.pathname;
return (
<div className={s['header-left']}>
<div className={s.button}>
<a href="#" onClick={this.handleClick}>
<FontAwesomeIcon icon={faBars} />
</a>
</div>
和折叠代码:
<Collapse isOpened={isOpened}>
<nav className={`${s.menu} ${s.mobile}`}>
<ul className={s['menu-ul']}>
...
</ul>
</nav>
</Collapse>
解决方案
您的onClick工作正常,但它没有重新呈现您的Reaction组件。您需要将isOpened
置于组件和全局变量的状态。请阅读this
class Header extends React.Component {
constructor(props){
super(props);
this.state = {isOpened: false};
}
handleClick = () => {
this.setState({isOpened: !this.state.isOpened});
};
render() {
const path = history.location && history.location.pathname;
return (
<div className={s['header-left']}>
<div className={s.button}>
<a href="#" onClick={this.handleClick}>
<FontAwesomeIcon icon={faBars} />
</a>
</div>
);
}
相关文章