2016-02-24 2 views
0

Ниже приведен фрагмент кода от navigation menu example, который от этого blogpost. То, что я не понимаю, - это использование метода self variable и bind.Передача переменной для функции через связывание в компоненте реакции

Я думаю this относится к MenuExample, когда он хранится как self, но я не знаю, как this изменилось внутри <li>?

Также почему onClick={this.clicked(index)} не работает? В этом контексте на что ссылается this?

var MenuExample = React.createClass({ 

getInitialState: function(){ 
    return { focused: 0 }; 
}, 

clicked: function(index){ 

    // The click handler will update the state with 
    // the index of the focused menu entry 

    this.setState({focused: index}); 
}, 

render: function() { 

    // Here we will read the items property, which was passed 
    // as an attribute when the component was created 

    var self = this; 

    // The map method will loop over the array of menu entries, 
    // and will return a new array with <li> elements. 

    return (
     <div> 
      <ul>{ this.props.items.map(function(m, index){ 

       var style = ''; 

       if(this.state.focused == index){ 
        style = 'focused'; 
       } 

       // Notice the use of the bind() method. It makes the 
       // index available to the clicked function: 

       return <li className={style} onClick={self.clicked.bind(self, index)}>{m}</li>; 

      }) } 

      </ul> 

      <p>Selected: {this.props.items[this.state.focused]}</p> 
     </div> 
    ); 

} 
}); 

// Render the menu component on the page, and pass an array with menu options 

ReactDOM.render(
    <MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />, 
    document.getElementById('container') 
); 
+0

https://medium.com/@john1jan/react-binding-revealed-aa458df8c136#.fd5z0vmjl – John

ответ

0

onClick={this.clicked(index)} не работает, потому что OnClick ожидает функции, а не результатом. Обычно в обработчике клика событие передается ему, но здесь они используют bind(), чтобы переопределить это поведение и передать компонент и индекс как «это» и первый аргумент. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

+0

'OnClick = {this.clicked.bind (это, индекс)}' также неправильно, это 'самообслуживания 'переменная необходимость, если да, то почему? 'this' первоначально ссылается на компонент и внутри onClick он меняет на что? – Ryan

+0

'this' переменная зависит от контекста. Назначая self и используя bind(), они удостоверяются, что правильное значение передается как 'this' в clicked() –

+0

Чтобы понять это лучше, я предлагаю вам добавить console.log (this) в ваш clicked() и попробовать несколько разных вариантов –

Смежные вопросы