我正在學習反應,並希望實現一個基本的導航欄中有一些項目,我想使最後一個我點擊有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中包裝所有東西,我們可以使用一些父母/孩子的回調,但是當孩子樹變得太深時,我害怕嗎?這是最佳做法? –