2017-12-30 18 views
0

수정하려는 사용자 정의 typeahead 구성 요소가 있습니다 & 부모로부터 자식으로 맞춤 onBlur 메서드를 전달하려고합니다.getDefaultProps()에서 액세스 할 때 구성 요소 메소드 액세스가 정의되지 않은 이유는 무엇입니까?

getDefaultProps: function() { 
    console.log(this.handleBlur) // undefined 
    return { 
     onChange: function() {}, 
     onBlur: this.handleBlur 
    } 
    } 

handleBlur 내가 액세스 할 구성 요소 내부 방법 :

나는 경우 onBlur에 정의 된 getDefaultProps는 전달되지 않는다있다. 거기에있는 컴포넌트 내부의 메소드에 어떻게 접근합니까?

답변

0

클래스가 인스턴스화되기 전에 내부적으로 React get가 기본 소품입니다. 즉, getDefaultProps 함수는 클래스의 정적 메서드입니다. createReactClass으로 반응 구성 요소를 만들면 그것이 정적 인 방법이라는 것은 분명하지 않습니다. 또 다른 방법은 내부의 blurHandler을 설정하는 것입니다 당신이 ES6을 사용하는 경우

// 1. Old JS: 
function Foo() {} 
Foo.staticFunction = function(){} 
var foo = new Foo(); 
// typeof Foo.staticFunction === 'function' 
// typeof foo.staticFunction === 'undefined' 

// 2. ES6: 
class Foo { 
    static myFunction =() => { ... } 
} 

당신이

// add the onBlur function outside of the class scope 
const handleBlur = event => { /* your fallback blur handler */ } 

class MyComponent extends Component { 
    static defaultProps = { 
     handleChange() {}, 
     handleBlur, 
    }; 
} 

뭔가를 작성할 수

자바 스크립트 정적 함수 또는 변수를 만드는 다른 방법이 있습니다 생성자 함수 :

class MyComponent extends Component { 
    constructor(props, context) { 
     super(props, context) 

     if (!this.props.blurHandler) { 
      this.blurHandler = this.defaultBlurHandler 
     } 
    } 
    defaultBlurHandler =() => { /* do your stuff here */ } 
} 
+0

불행히도 우리는 ES6 클래스를 사용하지 않습니다. 우리의 코드베이스에서. – thedeliciousmuffin