我已经通过reactJS完成了渲染
render(){
return (
<div>
<Router>
<div className="wrapper2">
<nav id="menu-principal" className="main menu-principal">
<ul>
<li><NavLink className="home-link" exact to="/">início</NavLink></li>
<li><NavLink exact to="/nota_biografica">nota biográfica</NavLink></li>
</ul>
</nav>
<div className="page-content">
<Route exact path='/nota_biografica' render={() => <NotaBiografica />} />
<Route exact path='/' render={() => <Home />} />
</div>
</div>
</Router>
</div>
)
}
当我单击包含“家庭链接”类的链接时,我想执行一些操作。就像我在下面的示例中尝试执行的操作无效。我该如何解决?谢谢。
var el = document.querySelector(".menu-principal");
el.onclick = (event) => {
for(var i = 0; i < el.childNodes.length; i++) {
if(el.childNodes[i].className === "home-link"){
alert('true')
}
}
}
答案 0 :(得分:2)
由于您定位的元素是<NavLink>
标签,该标签通常应导航到另一个路由器页面,所以我相信您所附加的事件将不会运行。我建议您不要使用<NavLink>
,而应在this.props.history.push('/path/to/route')
处理程序上使用onClick
(在导航到另一个路由地址之前,需要执行这些过程之后)。
在以下示例中,请注意withRouter
,我将<NavLink>
更改为span,然后将onHomeCLick
处理程序附加到它:
import React, {Component} from 'react';
import {withRouter, Route, BrowserRouter as Router} from "react-router-dom";
class YourComponent extends Component {
onHomeCLick = () => {
//DO something here prior to router navigation of ".home-link" element
this.props.history.push( '/' );
};
render(){
return (
<div>
<Router>
<div className="wrapper2">
<nav id="menu-principal" className="main menu-principal">
<ul>
<li><span className="home-link" onClick={this.onHomeCLick}>início</span></li>
<li><NavLink exact to="/nota_biografica">nota biográfica</NavLink></li>
</ul>
</nav>
<div className="page-content">
<Route exact path='/nota_biografica' render={() => <NotaBiografica />} />
<Route exact path='/' render={() => <Home />} />
</div>
</div>
</Router>
</div>
)
}
}
export default withRouter( YourComponent );
UPDATE ===========
如果您喜欢使用<NavLink>
,这是另一个技巧,唯一的解决方法是“回叫”方式。一旦您导航到该路线,它就会触发(我仍然看不到是否有办法在导航之前进行操作)。我们开始:
import React, {Component} from 'react';
import {Route, BrowserRouter as Router} from "react-router-dom";
class YourComponent extends Component {
isActive= (match, location) => {
if (match) {
console.log('Hi i am active, do something here');
}
return match;
};
render(){
return (
<div>
<Router>
<div className="wrapper2">
<nav id="menu-principal" className="main menu-principal">
<ul>
<li><NavLink className="home-link" activeClassName="active" isActive={this.isActive}>início</NavLink></li>
<li><NavLink exact to="/nota_biografica">nota biográfica</NavLink></li>
</ul>
</nav>
<div className="page-content">
<Route exact path='/nota_biografica' render={() => <NotaBiografica />} />
<Route exact path='/' render={() => <Home />} />
</div>
</div>
</Router>
</div>
)
}
}
export default YourComponent;