2016-09-22 2 views
0

아래 코드에서 누군가가 함수에 저장된 액세스 방법에 대해 조언 할 수 있습니까? 자식 QRScan 구성 요소로 전달되는 보조물 closeModal?하위 구성 요소의 함수에서 호출 할 수 있도록 소품을 통해 하위 구성 요소에 전달 된 함수에 바인딩하는 방법

나는 QRScan의 생성자에서 this.props.closeModal.bind(this)을 시도했지만 나는 _onBarCodeRead 기능에 this.props.closeModal()를 호출 할 때 나는 undefined is not an object (evaluating 'this.props.closedModal') 오류가 발생합니다.

소품이 확실히 생성자로 전달되는 중입니다. 함수를 올바르게 바인딩 할 수 없습니다. 도움이 많이 감사!

class Test extends React.Component { 

constructor(props) { 
    super(props); 
} 

_test(){ 
    console.log("test worked") 
} 

render() { 
    return (
    <View> 
     <QRScan closeModal={this._test}/> 
    </View> 
    } 
} 

아이 클래스 : 현재 위치에서 기능을 수정하지 않는 함수를 바인딩

class QRScan extends React.Component { 

constructor(props) 
{ 
super(props) 
console.log(this.props) 
this.props.closeModal.bind(this); 
} 

render() { 
    return (
    <BarcodeScanner 
     onBarCodeRead={this._onBarCodeRead} 
     width={windowWidth} 
     height={windowWidth * cameraAspectRatio} 
     style={styles.camera}> 
     <View style={styles.rectangleContainer}> 
     <View style={styles.rectangle} /> 
     </View> 
    </BarcodeScanner> 
); 
} 
_onBarCodeRead(e) { 
    console.log(e); 
    Vibration.vibrate(); 
    this.props.closeModal(); 
    } 
} 

답변

0

문제는 실제로 this._onBarCodeRead이 올바르게 바인딩되지 않았습니다. 하위 구성 요소의 생성자에서

당신은 대답은, 많은 감사 매우 단순 때 나는 그것을 싫어 this._onBarCodeRead = this._onBarCodeRead.bind(this);

+0

다음을 추가 할 필요가! –

0

. 대신 변수에 할당 할 수있는 결과 함수를 반환합니다.

따라서 이론적으로는 this.props.closeModal = this.props.closeModal.bind(this);을 할 수 있지만 반응이 없습니다. 그래서 대신 클래스에 메서드를 만들고 바인드하고 거기에서 소품에 액세스하는 것이 좋습니다. 예를 들면 :

물론
class QRScan extends React.Component { 

    constructor(props) 
    { 
    super(props) 
    this.closeModal = this.closeModal.bind(this) 
    } 
    closeModal() { 
    this.props.closeModal.call(this); 
    } 
} 

, 당신의 소품 방법에 전달하기보다는, 클래스 내에서 this을 유지 권합니다 일을 일반적으로 권장되는 방법.

코드를 작동 시키려면 this._onBarCodeRead 메서드를 사용하여 동일한 바인딩을 수행해야합니다.

관련 문제