2016-05-31 4 views
1

상태가 아닌 컨텍스트에 대한 모바일/플래시/터치 장치 감지를 위해 userAgent를 감지하기 위해 완료된 검사 (CDM에 구성 요소가 탑재 된 후)를 추가하고 싶습니다. 이것이 가능한가? 그렇다면 어떻게 할 수 있겠습니까? 나는 isFlashInstalled에 대한 컨텍스트 값에 액세스하려고 할 때 현재 undefined을 얻고 있습니다. 당신이 올바르게 설정 않은 상황에서 isFlashInstalled에 액세스하려고 할 때구성 요소가 React?에서 마운트 된 후 컨텍스트를 설정할 수 있습니까?

App.js

export class App extends Component { 
    static childContextTypes = { 
    isFlashInstalled: React.PropTypes.bool 
    }; 

    constructor() { 
    super(); 
    this.state = { 
     isFlashInstalled: false 
    }; 
    } 

    getChildContext() { 
    return { 
     isFlashInstalled: this.state.isFlashInstalled 
    }; 
    } 

    componentDidMount() { 
    const flashVersion = require('../../../client/utils/detectFlash')(); 
    // I know this could be done cleaner, focusing on how for now. 
    if (flashVersion && flashVersion.major !== 0) { 
     this.setFlashInstalled(true); 
    } else { 
     this.setFlashInstalled(false); 
    } 
    } 

    setFlashInstalled(status) { 
    this.setState({isFlashInstalled: status}); 
    } 
} 

나중에 내가 undefined

ChildComponent.js

export class ChildComponent extends Component { 
    // all the good stuff before render 
    render() { 
    const {isFlashInstalled} = this.context 
    console.log(isFlashInstalled); // undefined 
    } 
} 

답변

1

을 얻을 것이다 : 여기에 컨텍스트를 설정하는 구성 요소 엿볼입니다 부모 및 자식에 대한 최대 컨텍스트 유형 나는 테스트를하고는 비동기 상태를 설정 componentDidMount 참조 작동합니다

class Parent extends React.Component { 
    state = { 
    color: 'red' 
    } 

    getChildContext() { 
    return { 
     color: this.state.color 
    }; 
    } 

    componentDidMount() { 
    setTimeout(() => this.setState({color: 'blue'}), 2000) 
    } 

    render() { 
    return (
     <div>Test <Button>Click</Button></div> 
    ); 
    } 
} 

Parent.childContextTypes = { 
    color: React.PropTypes.string 
} 

class Button extends React.Component { 
    render() { 
    return (
     <button style={{background: this.context.color}}> 
     {this.props.children} 
     </button> 
    ); 
    } 
} 

Button.contextTypes = { 
    color: React.PropTypes.string 
}; 

http://jsbin.com/cogikibifu/1/edit?js,output

+0

내가 나를 위해하지만 당신의 대답은 분명 내가 표시하기 위하여려고하고 권리이기 때문에 작동하게 할 수없는 여전히 오전 답변으로 감사합니다 –

+0

감사합니다, 성공하길 바래요. –