我无法将菜单项连接到事件处理程序.这是一个UI模拟显示状态随时间的变化.这是一个下拉菜单(通过Bootstrap),根菜单项显示当前选择:
[ANN]最终目标是根据用户的选择异步更改页面内容.点击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
{item} ; }); return; } }); $(document).ready(function() { React.renderComponent( CurrentSelection(), document.getElementById('item-selection') ); });
- {this.state.title}
{itemNodes}
我几乎肯定我对javascript范围的朦胧理解是责备,但到目前为止我所尝试的一切都失败了(包括尝试通过道具传递处理程序).
问题是你使用匿名函数创建项目节点,而在里面this
意味着window
.修复是添加.bind(this)
到匿名函数.
var itemNodes = this.state.items.map(function (item) { return <li key={item}><a href='#' onClick={this.handleClick}>{item}</a></li>; }.bind(this));
或者创建一个副本this
并使用它:
var _this = this, itemNodes = this.state.items.map(function (item) { return <li key={item}><a href='#' onClick={_this.handleClick}>{item}</a></li>; })