我在将菜单项连接到事件处理程序时遇到问题。这是 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 传递处理程序)。

有帮助吗?

解决方案

问题是您正在使用匿名函数创建项目节点,并且在其中 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”的任务规范,解决方案可以如下(基于 React 组件和 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>
    )
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top