当您在 render 方法中单击 anchor 标记时,我正在尝试更新我的组件状态。我已经尝试在构造函数内部进行绑定(bind),但仍然没有调用 console.log。下面是我的代码。请帮忙。这阻碍了我的进步,哈哈。
这是根据我之前在 stackoverflow 上的问题修改的代码。
const React = require('react');
class Navbar extends React.Component {
constructor(...props) {
super(...props);
this.setActiveTab = this.setActiveTab.bind(this)
this.state = {
currentPage: "/"
}
}
setActiveTab(e) {
console.log(e.target)
this.setState({
currentPage: e.target.href
})
}
render() {
const { path } = this.props
let classString = path === this.state.currentPage ? 'nav-item is-tab is-active' : 'nav-item is-tab'
return (
<nav className="nav">
<div className="nav-left">
<a className="nav-item">
<h1>CREATORS NEVER DIE</h1>
</a>
</div>
<div className="nav-right nav-menu">
<a href="/" className={classString} onClick={this.setActiveTab}>
Home
</a>
</div>
</nav>
)
}
}
module.exports = Navbar;
最佳答案
您需要在点击处理程序中使用 e.preventDefault()
。
它正在触发,但 anchor 的默认行为是刷新页面,所以它只是立即重新呈现。
关于javascript - anchor 标记没有调用 React 中的 onClick 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44292187/