我在将菜单项连接到事件处理程序时遇到问题。下面是显示状态随时间变化的 UI 的模拟。这是一个下拉菜单(通过引导),根菜单项显示当前选择:
[ANN]<click ... [ANN] ... [BOB]<click ... [BOB]
[Ann] [Ann]
[Bob]<click + ajax [Bob]
[Cal] [Cal]
最终目标是根据用户的选择异步更改页面内容。点击鲍勃应该触发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传递处理程序)。
问题是您正在使用匿名函数创建项目节点,在该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>;
})
正如我能理解"Anna"、"Bob"、"Cal"的任务规范,解决方案可以是以下(基于反应组件和 ES6):
基本现场演示在这里
import React, { Component } from "react"
export default class CurrentSelection extends Component {
constructor() {
super()
this.state = {
index: 0
}
this.list = ["Anna", "Bob", "Cal"]
}
listLi = list => {
return list.map((item, index) => (
<li key={index}>
<a
name={item}
href="#"
onClick={e => this.onEvent(e, index)}
>
{item}
</a>
</li>
))
}
onEvent = (e, index) => {
console.info("CurrentSelection->onEvent()", { [e.target.name]: index })
this.setState({ index })
}
getCurrentSelection = () => {
const { index } = this.state
return this.list[index]
}
render() {
return (
<div>
<ul>{this.listLi(this.list)}</ul>
<div>{this.getCurrentSelection()}</div>
</div>
)
}
}