2016-05-31 38 views
1

我希望添加检查完成(一旦组件安装在CDM中)来检测userAgent - 为移动/闪光/触摸设备检测的目的而不是状态。这可能吗?如果是的话,你会怎么做?当我尝试访问isFlashInstalled的上下文值时,我正在获取undefined。这里是窥探​​组件设置背景:组件在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}); 
    } 
} 

后来试图访问从上下文isFlashInstalled时,我会得到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

谢谢你,希望你会成功 –

相关问题