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

ありがとう、あなたが成功することを願って –

関連する問題