ReactJS 无法访问“this";方法 [英] ReactJS can't access "this" methods

查看:47
本文介绍了ReactJS 无法访问“this";方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将方法传递给子组件以处理 onclick 事件.我在网上看到了很多例子,但我无法让它工作.当我在父级的渲染函数中并尝试将this.handleClick"传递给子级时,handleClick 未定义.

看看ThumbList的render方法:

var Thumb = React.createClass({句柄点击:函数(){控制台日志(这个)console.log('handleClick of Thumb')this.props.onClick()},渲染:函数(){返回(<div className="thumb" key={this.props.thumb.url}><a href='#' onClick={this.handleClick}><img src={'/img/rings/thumbs/'+this.props.thumb.url+'_thumb.jpg'} alt="图片"></img></a>

);}});var ThumbList = React.createClass({handleClick: 函数 (id) {console.log('点击 ThumbList');},从服务器加载:函数(){$.ajax({网址:戒指/imgs/5",数据类型:'json',成功:功能(数据){this.setState({数据: 数据});}.bind(this),错误:函数(xhr,状态,错误){console.error('rings/imgs/5', status, err.toString());}.绑定(这个)});},getInitialState: 函数(){返回{数据:[]};},componentDidMount: 函数(){this.loadFromServer();setInterval(this.loadFromServer, 2000);},渲染:函数(){var handlefunc=this.handleClickvar thumbsNodes = this.state.data.map(function(thumb) {console.log(this.handleClick)//未定义!console.log(handlefunc)//正在工作返回 (<Thumb thumb={thumb} key={thumb.url} onClick={handlefunc.bind(this,thumb.url)}/>);});返回(<div className="col-md-1 col-md-offset-1" id='thumbs'>{thumbsNodes}

);}});

知道我可能遗漏了什么吗?

解决方案

如果您使用 Babel 这样的编译器作为开发工作流程的一部分,我建议您使用 箭头函数:

var thumbsNodes = this.state.data.map((thumb) => {console.log(this.handleClick);return <Thumb thumb={thumb} key={thumb.url}onClick={this.handlefunc.bind(this,thumb.url)}/>;});

如您所见,这是一个很好的紧凑语法.箭头函数将为您保留 this 上下文.Babel 编译器生成使用闭包的 JavaScript:

var thumbsNodes = this.state.data.map(function(thumb) {var _this = this;console.log(_this.handleClick);return <Thumb thumb={thumb} key={thumb.url}onClick={_this.handlefunc.bind(_this,thumb.url)}/>;});

I am trying to pass a method to a child component to handle onclick events. I saw a lot of examples online, but I can't get it working. When I am inside the render function of the parent and trying to pass "this.handleClick" to the child, handleClick is undefined.

Have a look at render method of ThumbList:

var Thumb = React.createClass({
        handleClick: function() {
            console.log(this)
            console.log('handleClick of Thumb')
            this.props.onClick()
        },
        render: function() {
            return(
                    <div className="thumb" key={this.props.thumb.url}>
                        <a href='#' onClick={this.handleClick}>
                            <img src={'/img/rings/thumbs/'+this.props.thumb.url+'_thumb.jpg'} alt="Image"> 
                            </img>         
                        </a>
                    </div>
                );
        }
    });

    var ThumbList = React.createClass({

        handleClick: function (id) {
            console.log('click of ThumbList');

        },


        loadFromServer: function() {
            $.ajax({
                url: 'rings/imgs/5',
                dataType: 'json',
                success: function(data) {
                    this.setState({data: data});
                }.bind(this),
                error: function(xhr, status, err) {
                    console.error('rings/imgs/5', status, err.toString());
                }.bind(this)
            });
        },
        getInitialState: function(){
            return {data: [] };
        },
        componentDidMount: function(){
              this.loadFromServer();
                setInterval(this.loadFromServer, 2000);
                },

        render: function() {
            var handlefunc=this.handleClick
            var thumbsNodes = this.state.data.map(function(thumb) {
                console.log(this.handleClick)  // is Undefined!
                console.log(handlefunc)   // is working
                return (
                        <Thumb thumb={thumb} key={thumb.url} onClick={handlefunc.bind(this,thumb.url)}/>
                );
            });

            return(
                        <div className="col-md-1 col-md-offset-1" id='thumbs'>
                            {thumbsNodes}
                        </div> 

                );
            }

    });

Any idea what I might be missing?

解决方案

If you're using a compiler like Babel as part of your development workflow, I'd suggest using arrow functions:

var thumbsNodes = this.state.data.map((thumb) => {
  console.log(this.handleClick);
  return <Thumb thumb={thumb} key={thumb.url} 
                onClick={this.handlefunc.bind(this,thumb.url)}/>;
});

As you can see, it's a nice compact syntax. The arrow function will preserve the this context for you. The Babel compiler produces JavaScript that uses a closure:

var thumbsNodes = this.state.data.map(function(thumb) {
  var _this = this;
  console.log(_this.handleClick);
  return <Thumb thumb={thumb} key={thumb.url} 
                onClick={_this.handlefunc.bind(_this,thumb.url)}/>;
});

这篇关于ReactJS 无法访问“this";方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆