onClick-in-reactjs不工作

onClick-in-reactjs不工作,reactjs,Reactjs,下面是我的代码。我的onClick不起作用。它总是通过错误UncaughtTypeError:无法读取未定义的属性'likeQuestion'。但我的gotoPage功能正在运行。我不知道我错在哪里。我是个新手。为什么likeQuestion函数不被识别 我的第一次点击是工作 导出默认类问题扩展React.Component{ 建造师{ 超级的 this.toggle=this.toggle.bindthis; 此.state={ 页码:1, dropdownOpen:false, 问题信息:[

下面是我的代码。我的onClick不起作用。它总是通过错误UncaughtTypeError:无法读取未定义的属性'likeQuestion'。但我的gotoPage功能正在运行。我不知道我错在哪里。我是个新手。为什么likeQuestion函数不被识别

我的第一次点击是工作

导出默认类问题扩展React.Component{ 建造师{ 超级的 this.toggle=this.toggle.bindthis; 此.state={ 页码:1, dropdownOpen:false, 问题信息:[] } } 组件将安装{ //一些行动 } 戈托帕金指数{ //一些行动,这是有效的 } 拨动{ 这是我的国家{ dropdownOpen:!this.state.dropdownOpen }; } 利基奎斯特酒店{ console.log'this clicked'; //但这是行不通的 } 渲染{ var canvasses=this.state.questionItem.mapfunctiondata,i{ var firstLtr=data.user\u name.charAt0; 回来 {firstLtr}{data.user_name} {data.message} 不讨论 this.likeQuestioni}>{data.likes}likes ; }; 回来 页 {pgrow}

页面:{currentPage}

{画布} }
尝试使用箭头函数定义助手函数

 gotoPage = (index) => {

      //some action. This is working
    }

  toggle = () => {
    this.setState({
      dropdownOpen: !this.state.dropdownOpen
    });
  }

 likeQuestion = (e) => {
    console.log('this is clicked');
    //But this is not working
 }

在React组件的构造函数中绑定这些方法。e、 g

this.likeQuestion = this.likeQuestion.bind(this);
// Needs to be done for all the helper methods.
这样您就可以访问该上下文中的类级别

例如,最小设置

类问题扩展了React.Component{ 构造器{ 超级作物; 此.state={ 喜欢:10 }; } likeQuestion=e=>{ console.log'this clicked'; //但这是行不通的 } 渲染{ 返回
<按钮大小=sm 颜色=链接 className=disassionspan onClick={ i=>this.likeQuestioni } > { 这个州喜欢什么 } 喜欢
; } }; ReactDOM.render,document.querySelector'test';
React不会在渲染内部自动绑定贴图,所以您必须自己进行绑定才能使用它并调用this.likeQuestion。幸运的是,map提供了第二个参数来指定此上下文

所以只要用

this.state.questionItem.map(function(data,i) {
  ...
}, this)
而不是

this.state.questionItem.map(function(data,i) {
  ...
})
选项2:在地图中使用箭头函数,如mapdata,i=>

选项3:将其绑定到组件构造函数中的likeQuestion


添加这个很酷,谢谢。你能解释一下为什么它会起作用吗?React不会在render中自动绑定map方法,所以你必须自己做,乐意帮忙-你能帮我做一件事吗?我正在传递一个参数,这个参数是由一个api获取的,当页面加载时单击onclick。onClick={this.likeQuestionthis,data.question\u url}您需要onClick={=>this.likeQuestionthis,data.question\u url}。如果仍然不清楚,请发一个新问题,并用一个例子来更新答案。现在我答对了。aftr在render中添加此项。谢谢您的帮助。您能帮我做一件事吗?我正在传递api获取的参数,在加载页面时单击onclick。onClick={this.likeQuestionthis,data.question\u url}