2017-01-03 4 views
2
에서 매개 변수가있는 생성자의 기능을 결합하는 방법

그래서 여기 내 함수의는 Reactjs

constructor() 
{ 
    this.remove = this.remove.bind(this); 
} 
render() 
{ 
    return (
     <div> 
      { this.state.search.map((item, index) => 
       ( 
        <button key={index} onClick={this.remove(item)}>{item.search}: {item.text}</button> 
       )) 
      } 
      </div> 
     </div> 
    ); 
} 

하지만 제대로 작동하면 생성자에서 바인딩을 제거하고 (사실 상관 없음)이 단추를 다음과 같이 변경하십시오.

<button key={index} onClick={this.remove.bind(this, item)}>{item.search}: {item.text}</button> 

내 궁금한 점은 매개 변수를 사용할 수 있도록 생성자에서 바인딩하는 방법이 있습니까?

답변

3

this.remove(item)this.remove.bind(this, item)의 차이는 첫 번째 은 기능이이고 두 번째는 새로운 기능을 생성한다는 것입니다. 불필요한 비록

So my question is, is there a way to bind it in the constructor so that it can take on the parameter?

당신은, this.remove.bind(this, item)이 (가) 생성자를 바인딩을 수행 할 수 있습니다. 이벤트 핸들러에 item를 전달하려는 경우

는, 당신은 당신의 현재 설정과, item에 액세스 할 수 있습니다 .map에 새로운 기능을 만들에 있습니다 . 이것은 .bind 또는 폐쇄를 통해 이루어질 수 있습니다. 두 경우 모두 생성자에서의 바인딩은 단순히 필요하지 않습니다.

item과 다른 방식으로 제공하는 경우에만 새 기능을 만들 수 있습니다.

function Button({item, onClick}) { 
    return <button onClick={() => onClick(item)}>{item.search}: {item.text}</button>; 
} 

class Component extends React.Component { 
    constructor() 
    { 
     this.remove = this.remove.bind(this); 
    } 

    render() 
    { 
     return (
      <div> 
       { this.state.search.map((item, index) => 
        ( 
         <Button key={index} onClick={this.remove} item={item} /> 
       )) 
       } 
       </div> 
      </div> 
    ); 
    } 
} 
+0

난 그냥 더 나은 시작을 결합하는 원칙을 실천 한 것을 읽어 : 맞아요 –

+1

\하지만 소품 (그러므로 더 아래 함수 생성을 밀어)로 item 소요 다른 구성 요소와 단추를 포장 함수를 다른 구성 요소로 직접 전달하는 경우에만 작동합니다. 그것에 대해 생각해보십시오 : * this * remove * 함수가 있습니다. 이 함수가 다른'item' 값으로 * n 번 * 실행되기를 원합니다. 올바른'item' 값으로'this.remove'를 호출하는 * n * 함수를 생성하거나 함수 호출을 스택 아래로 더 밀어 넣어야합니다. –

+0

해명 해 주셔서 감사합니다. –