我无法将菜单项与事件处理程序连接起来。这里是一个 UI 的模拟,显示随时间的状态变化。它是一个下拉菜单(使用 Bootstrap),根菜单项显示当前选择:
[ANN]<click ... [ANN] ... [BOB]<click ... [BOB]
[Ann] [Ann]
[Bob]<click + ajax [Bob]
[Cal] [Cal]
最终目标是根据用户的选择异步更改页面内容。点击Bob应该触发handleClick
,但没有。
另外,我对componentDidMount调用this.handleClick();
的方式并不满意,但暂时可以作为从服务器获取初始菜单内容的一种方式。
/** @jsx React.DOM */
var CurrentSelection = React.createClass({
componentDidMount: function() {
this.handleClick();
},
handleClick: function(event) {
alert('clicked');
// Ajax details ommitted since we never get here via onClick
},
getInitialState: function() {
return {title: "Loading items...", items: []};
},
render: function() {
var itemNodes = this.state.items.map(function (item) {
return <li key={item}><a href='#' onClick={this.handleClick}>{item}</a></li>;
});
return <ul className='nav'>
<li className='dropdown'>
<a href='#' className='dropdown-toggle' data-toggle='dropdown'>{this.state.title}</a>
<ul className='dropdown-menu'>{itemNodes}</ul>
</li>
</ul>;
}
});
$(document).ready(function() {
React.renderComponent(
CurrentSelection(),
document.getElementById('item-selection')
);
});
我几乎可以肯定我的对JavaScript作用域的模糊理解是有问题的,但到目前为止,我尝试过的所有方法都失败了(包括尝试通过props向下传递处理程序)。
map
一个第二个参数this
,它将作为上下文来执行映射函数。 - Sophie Alpertmap
,以使其更易读,将this
作为第二个参数:var itemNodes = this.state.items.map(this.itemNode, this);
- clozachvar itemNodes = this.state.items.map(this.itemNode)
。 - WickyNilliams