我正在学习反应,并希望实现一个基本的导航栏中有一些项目,我想使最后一个我点击有className活动和所有其他没有。从反应更新兄弟对象
在下面的代码中,我无法删除resetALL与item.setState中的className(是通过阅读文档我明白它不起作用),所以我试图直接使用jQuery操纵dom。它在第一次点击时有效,但第二次点击没有效果。有没有任何反应原生的方式来做到这一点?谢谢。
$(document).ready(function(){
var NavItem = React.createClass({
getInitialState: function() {
return this.props.item;
},
handleClick: function() {
React.render(<span>{this.props.item.description}</span>, document.getElementById('main'));
this.props.resetALL();
console.log("this", this);
this.setState({active: true});
},
render: function() {
var className = this.state.active ? "active" : "";
return <li className={className}><a href="#" onClick={this.handleClick}>{this.props.item.description}</a></li>;
}
});
var NavBar = React.createClass({
items : [],
resetALL: function() {
this.items.forEach(function(item) {
console.log("item", item);
// item.setState({active: false});
});
$("#nav-sidebar li").each(function(){
$(this).removeClass("active");
});
},
render: function() {
var _this = this;
this.props.items.forEach(function(item) {
console.log("handleClick", this.handleClick);
_this.items.push(<NavItem item={item} key={item.id} resetALL={_this.resetALL}/>);
});
return (
<ul className="nav nav-sidebar" id="nav-sidebar">
{this.items}
</ul>
);
}
});
var NAVLIST = [
{id: 1, description: 'OverView', active: true},
{id: 2, description: 'Calls'},
{id: 3, description: 'Channels'},
{id: 4, description: 'OverView'}
]
React.render(<NavBar items = {NAVLIST} />, document.getElementById('sidebar'));
React.render(
<h1>Hello, FreeSWITCH!</h1>,
document.getElementById('main')
);
});
谢谢,现在我明白了。 ottonomy的解决方案现在适用于我。我最终将使用一个应用程序来追踪我所想的一切。 –
嗯,你不需要跟踪所有的东西,但它会很好:) – Cristik
嗯,我的意思是它可以跟踪一切,如果我想。正如你所提到的,我每次点击一个Item时都会重新呈现主要元素,这就像切换页面一样。它的作用虽然不是反应的目的。但是Navbar和main元素是两个不同的元素,我必须使用window.addEventListener的子PubSub来让它们相互交谈,正如http://maketea.co.uk/2014/03/05/building-robust- web-apps-with-react-part-1.html。如果在App中包装所有东西,我们可以使用一些父母/孩子的回调,但是当孩子树变得太深时,我害怕吗?这是最佳做法? –