문제

하는 데 문제가 있습니다 메뉴 항목이 연결되어 있는 이벤트 처리기입니다.여기의 모형의 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')
  );
});

나는 거의 긍정적인 내 흐릿한 이해를 자바 스크립트의 범위는 비난하고는,그러나 모든 것을 내가 지금까지 시도했지 못했(려고 노력을 포함하여 전달하는 핸들러를 통해 소품이다).

도움이 되었습니까?

해결책

문제는 너를 만드 항목을 사용하여 노드 익명의 기능,내부는 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>
    )
  }
}
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top