报错代码如下:(用箭头函数)handlePublish2=()=>{console.log(this.state.comment)}'handlePublish2'isnotdefinedno-undefSearchforthekeywordstolearnmoreabouteacherror.换了种写法就没报错:handlePublish2(){console.log(this.state.comment)}//不过要手动绑定一下,感觉没个函数都要绑定,好麻烦=。=this.handlePublish=this.handlePublish.bind(this)为什么用箭头函数就不行额。。我看网上的代码都是可以的,求解完整代码:importReact,{Component}from'react';exportdefaultclassPublishextendsComponent{constructor(){super()this.state={username:'',comment:'',commentArr:[]}this.handlePublish=this.handlePublish.bind(this);this.handleNameChange=this.handleNameChange.bind(this);this.handleCommentChange=this.handleCommentChange.bind(this);}handlePublish(){const{username,comment}=this.stateif(!username){alert('请输入用户名')return}if(!comment){alert('请输入内容')return}this.state.commentArr.push({username:this.state.username,comment:this.state.comment})this.reset()this.forceUpdate()}handleNameChange(e){this.setState({username:e.target.value})}handleCommentChange(e){this.setState({comment:e.target.value})}reset(){this.setState({username:'',comment:'',})}handlePublish2=()=>{console.log(this.state.comment)}render(){letcommentArr=this.state.commentArr.map((comment,idx)=>{return( {comment.username}--{comment.comment}
)})return(
发布
{commentArr}
)}}
慕哥9229398
眼眸繁星
相关分类