2016-12-19 4 views
2

아래 코드는 제 코드입니다. 내 onClick이 작동하지 않습니다. 그것은 항상 "Uncaught TypeError : 정의되지 않은"likeQuestion '속성을 읽을 수 없습니다. 하지만 내 "gotoPage"기능이 작동 중입니다. 나는 내가 어디 잘못되었는지 모른다. 나는 Reactjs에서 아주 새롭다. "likeQuestion"기능이 인식되지 않는 이유는 무엇입니까? onClick in reactjs not working

나의 첫번째 온 클릭

은 반작용 구성 요소의 constructorarrow 기능

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 
} 

또는

바인딩이 방법을 사용하여 도우미 함수를 정의하는

export default class Question extends React.Component { 
    constructor(){ 
    super(); 
    this.toggle = this.toggle.bind(this); 
    this.state = { 
     pageNo : 1, 
     dropdownOpen: false, 
     questioninfo : [] 
     } 
    } 
    componentWillMount(){ 
    //some action 
    } 

    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 
} 


render() { 
     var canvases = this.state.questionItem.map(function(data,i) { 
      var firstLtr = data.user_name.charAt(0); 

      return (
       <div key={i}> 
        <Col sm="12" md={{ size: 12, offset: 2 }} className="questionCard"> 
         <Card block> 
         <CardTitle> 
           <div className="outerCircle"><span>{firstLtr}</span></div> {data.user_name} 
           <i className="fa fa-flag-o flagging" aria-hidden="true"></i> 
           <a href={data.location_url} target="_blank" className="questionLocation">{data.location_url}</a> 
         </CardTitle> 
         <CardText className="questionTxt">{data.message}</CardText> 
         <div> 
          <Button className="replyBtn" disabled>No Discussion</Button> 
          <Button size="sm" color="link" className="disussionSpan" onClick={(i) => this.likeQuestion(i)}>{data.likes} Likes</Button> 
         </div> 
         </Card> 
        </Col> 
       </div> 
      ); 
     }); 

    return(
     <div className="container"> 
     <div className="row"> 
     <div className="pageInfo"> 
     <Dropdown className="inline" isOpen={this.state.dropdownOpen} toggle={this.toggle}> 
      <DropdownToggle caret> 
      Pages 
      </DropdownToggle> 
      <DropdownMenu> 
      {pgrow} 
      </DropdownMenu> 
     </Dropdown> 
     <p className="inline currPgNo">Page: {currentPage}</p> 
     </div> 
      <div className="col-md-8 col-md-offset-2"> 

       {canvases} 
      </div> 
     </div> 

     </div> 
    ) 
    } 

답변

2

render() 안에 것없는 자동 바인드 맵 반응 최소한의 설정을. 운좋게도 map은 context (this)을 지정하는 두 번째 인수를 제공합니다.


그래서 그냥 ...

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

대신

사용
this.state.questionItem.map(function(data,i) { 
    ... 
}) 
  • 옵션 2 : 맵 사용 화살표 기능과 같은 map((data, i) => ...

  • 옵션 3 : 이것을 다음에 바인딩하십시오. 구성 요소의 생성자에 likeQuestion.

+0

이것을 추가해 주셔서 감사합니다. 왜 그것이 효과가 있었는지 설명해 주시겠습니까? – Sidhemu

+0

React는 render() 내에서 자동으로 맵 메서드를 자동 바인드하지 않으므로 직접 수행해야합니다. – lustoykov

+0

ok. 고맙습니다. @leo – Sidhemu

2

시도를하고있다. 예 :

this.likeQuestion = this.likeQuestion.bind(this); 
// Needs to be done for all the helper methods. 

그러면 레벨 this에 액세스 할 수 있습니다.

예컨대 당신이 this을 사용하고 this.likeQuestion를 호출하기 위해 스스로를해야하므로

class Question extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 

 
    this.state = { 
 
     likes:10 
 
    }; 
 
    } 
 

 

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

 
    return (<div> 
 
     < button size = "sm" 
 
     color = "link" 
 
     className = "disussionSpan" 
 
     onClick = { 
 
     (i) => this.likeQuestion(i) 
 
     } > { 
 
     this.state.likes 
 
     } 
 
     Likes < /button> 
 

 
      </div> 
 
    ); 
 
    } 
 

 
}; 
 

 
ReactDOM.render(< Question/> , document.querySelector('#test'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="test"> 
 
</div>

+0

여전히 같은 오류가 발생합니다. – Sidhemu

+0

같은 오류가 발생합니까? – WitVault

+0

예를 들어 답이 업데이트되었습니다. – WitVault