javascript - 在class中调用this.props.title.length报错
怪我咯
怪我咯 2017-04-11 13:22:05
[JavaScript讨论组]

render(){
    return(
    //这里调用.length是成功执行的
        {alert(this.props.rightTitle.length)}}>
            
                {this.props.title}
                {this.renderRightView()}
            
        
    )
}

renderRightView=()=>{
    if(this.props.isSwitch){
        return (
            {this.setState({isOn:!this.state.isOn})}} style={{marginRight:8}}/>
        )
    }
    else{
        return(
            
                {this.rightTitleView()}
                
            
        )
    }
}

rightTitleView(){
//这里调用.length是会报错的
    if(this.props.rightTitle.length)
    {
        return(
            {this.props.rightTitle}
        )
    }
}

具体错误是:undefined is not an object (evaluating this.props.rightTitle.length)

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(4)
巴扎黑
是不是rightTitleView()应该写成rightTitleView=()=>{}
PHPz

rightTitleView需要绑定this,否则获取不了props。

PHP中文网

好端端的renderRightView()为什么要写成箭头函数?
箭头函数是回调,回调就要bind(this)。

巴扎黑

这边this已经指向TouchableOpacity 了,当然没了,可以手动绑定this,一般是在constructor()函数中,

this.renderRightView = this._renderRightView.bind(this)
this.rightTitleView = this._rightTitleView.bind(this)

也可以用autobind-decorator库来解决这个问题,但是这个需要用到装饰器,需要进行转换一下,配置一下babel就可以

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号