在map函数内部的回调函数

3

我刚接触Reactjs,并正在使用Cordova和Reactjs制作目录浏览应用程序。

目前,我遇到了错误this.props.onClick不是一个函数,我发现this.props.onClick未定义。请查看我的代码如下:

var RepositoryList = React.createClass({
    //updating the list from a child folder entry
    updateListFromChild:function(childFolder){ 
        console.log("in parent update");
    },    
    render:function(){
        console.log(this.updateListFromChild); //function()
        var itemsInRepo = this.props.items.map(function(entry){
            console.log("in map: " + this.updateListFromChild); //undefined
            return (
                <RepositoryEntry repositoryItem={entry} 
                                 folderOnClick={this.updateListFromChild} />
            );
        });
        return (
            <ul className="table-view">
                {itemsInRepo}
            </ul>
        );
    }
});

folderOnClick 属性未定义。但我不知道如何解决这个问题。有人能指出吗?

2个回答

6
一般来说 - 这是JavaScript中的“动态this”问题
然而,由于您正在使用带有JSX的ReactJS,因此您的代码已经在转换中支持了ES6箭头函数:
var itemsInRepo = this.props.items.map(entry => (                
   <RepositoryEntry repositoryItem={entry} folderOnClick={this.updateListFromChild} />
));

您可以在MDN上查看更多示例的语法。


0
我们也可以采用这种方式。以下是代码片段:
var itemsInRepo = this.props.items.map( 
        function(entry){                
            return(
             <RepositoryEntry 
               repositoryItem={entry} 
               folderOnClick={this.updateListFromChild} 
        />);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接