繁体   English   中英

React.js中的这个关键字

[英]This keyword in React.js

有功能

changeSong: function(index) {
    this.setState({currentSongIndex: index };
}

我需要通过单击div来运行将索引作为参数传递的changeSong函数

var listTemp = data.map(function(item,index) {

        var listTemp = data.map(function(item,index) {

        return (
            <div key={index} className="eachTrack" onClick={this.changeSong({index})}>
                <span className="duration">{item.duration}</span>
                <a href="#" className="songTemplate" >{item.artist} - {item.track}</a>

            </div>  
        )
    }.bind(this))

它只是运行我的changeSong函数3次(与我拥有div元素一样多)。 现在,它甚至没有传递“ index”参数就运行了,单击也没有任何事件。

您需要将此绑定

var listTemp = data.map(function(item,index) {
  return (
            <div key={index} className="eachTrack" onClick={this.changeSong({index})}>
                <span className="duration">{item.duration}</span>
                <a href="#" className="songTemplate" >{item.artist} - {item.track}</a>

            </div>  
        )
    }.bind(this))

或通入地图功能这样的

var listTemp = data.map(function(item,index) {
  return (
            <div key={index} className="eachTrack" onClick={this.changeSong({index})}>
                <span className="duration">{item.duration}</span>
                <a href="#" className="songTemplate" >{item.artist} - {item.track}</a>

            </div>  
        )
    }, this)

正如其他人所指出的那样,您可能希望将changeSong函数包装在箭头函数中,以便它不会在render上立即执行:

<div key={index} className="eachTrack" onClick={() => this.changeSong(index)}>

您应该使用.bind(...)或通过向.map(...)提供context参数来this绑定上下文。 另外,请确保提供适当的函数作为事件处理程序。 特别是,将处理程序包装在箭头函数中,以在事件分派时正确传递index

<div key={index} className="eachTrack" onClick={() => this.changeSong(index)}>

使用纯ES5 Javascript时,您需要this显式绑定到函数。 幸运的是, Array.prototype.map this上下文使用了第二个参数。

var listTemp = data.map(function(item,index) {

        return (
            <div key={index} className="eachTrack" onClick={this.changeSong({index})}>
                <span className="duration">{item.duration}</span>
                <a href="#" className="songTemplate" >{item.artist} - {item.track}</a>

            </div>  
        )
    }, this); // Passes in the parent `this` context to the map callback function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM