Ниже приведен фрагмент кода от 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')
);
https://medium.com/@john1jan/react-binding-revealed-aa458df8c136#.fd5z0vmjl – John