通过反应组件

时间:2016-02-24 19:38:17

标签: reactjs

以下是navigation menu example的代码段,来自此blogpost。我不明白的是使用自变量和绑定方法。

我认为this在存储为self时会引用MenuExample,但我不知道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')
);

1 个答案:

答案 0 :(得分:0)

onClick={this.clicked(index)}不起作用,因为onClick需要一个函数,而不是它的结果。通常,在单击处理程序中,事件将传递给它,但是在这里它们使用bind()来覆盖该行为,并将组件和索引作为“this”和第一个参数传递。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind