目前在 reactjs 中构建一个应用程序并遇到了一个奇怪的问题。JSX 代码如下(抱歉有点冗长):
var NavigationTab = React.createClass({
onClick: function() {
console.log('NT' + this.props.tab.index);
this.props.onTabClick(this.props.tab.index);
},
render: function(index){
return (
<li>
<a href="#" onClick={this.onClick} className='navigation-tab'> {this.props.tab.title} </a>
</li>
)
}
});
var NavigationPanel = React.createClass({
getInitialState: function() {
return {
};
},
onTabClick: function(tab) {
//console.log(i) ;
this.setState({active : tab});
this.props.showTab(tab);
},
render: function() {
var self = this;
var tabs = this.props.tabs.map(function(item, index){
item.index = index;
return <NavigationTab tab={item} onTabClick={self.onTabClick} />;
});
return (
<div id='navigation-panel' className='col-xs-2'>
<ul className='nav nav-pills nav-stacked'>
{tabs}
</ul>
</div>
);
}
});
var App = React.createClass({
getInitialState: function() {
return {
tabs: [
{title: 'test', ref: 'test', content: <div> test </div>},
{title: 'Dasboard', ref: 'dashboard', content: <div> home </div>},
{title: 'Settings', ref: 'settings', content: <div> settings </div>},
{title: 'Logout', ref: 'logout', content: <div> logout </div>}
],
activeTab: 0};
},
showTab : function(index) {
console.log('AP ' + index);
this.setState({activeTab : index});
},
render: function() {
console.log('AP ' + this.state.activeTab);
console.log('AP ' + this.state.tabs[this.state.activeTab].title);
return (
<div id="container">
<NavigationPanel showTab={this.showTab} tabs={this.state.tabs} />
<div id="content-body">
{this.state.tabs[this.state.activeTab].content} /* [1] */
</div>
</div>
);
}
});
改变标签后会发生什么,第一个标签“测试”将不再显示。
如果我将行更改/* [1] */
为{this.state.tabs[this.state.activeTab].ref}
它,它会按预期工作。
这是一个小提琴