Reactjs 是否可以在组件装入React后设置上下文?

Reactjs 是否可以在组件装入React后设置上下文?,reactjs,redux,Reactjs,Redux,我希望将所做的检查(一旦组件安装到CDM中)添加到检测userAgent中,以便移动/闪存/触摸设备检测到上下文,而不是状态。这可能吗?如果是,你会怎么做?当我尝试访问isFlashInstalled的上下文值时,我当前得到了undefined。下面是对设置上下文的组件的概述: App.js 导出类应用程序扩展组件{ 静态childContextTypes={ isFlashInstalled:React.PropTypes.bool }; 构造函数(){ 超级(); 此.state={ isF

我希望将所做的检查(一旦组件安装到CDM中)添加到检测userAgent中,以便移动/闪存/触摸设备检测到上下文,而不是状态。这可能吗?如果是,你会怎么做?当我尝试访问
isFlashInstalled
的上下文值时,我当前得到了
undefined
。下面是对设置上下文的组件的概述:

App.js

导出类应用程序扩展组件{
静态childContextTypes={
isFlashInstalled:React.PropTypes.bool
};
构造函数(){
超级();
此.state={
isFlashInstalled:错误
};
}
getChildContext(){
返回{
isFlashInstalled:this.state.isFlashInstalled
};
}
componentDidMount(){
const flashVersion=require('../../../client/utils/detectFlash')();
//我知道这可以做得更干净,现在就专注于如何做。
如果(flashVersion&&flashVersion.major!==0){
此.setFlashInstalled(true);
}否则{
此.setFlashInstalled(错误);
}
}
setFlashInstalled(状态){
this.setState({isFlashInstalled:status});
}
}
稍后,当尝试从上下文访问isFlashInstalled时,我将获得未定义的

ChildComponent.js

导出类ChildComponent扩展组件{
//渲染前所有的好东西
render(){
const{isFlashInstalled}=this.context
console.log(isFlashInstalled);//未定义
}
}

您是否正确设置了父级和子级的上下文类型?我做了一个测试,它运行正常,请参阅异步设置状态的componentDidMount:

类父级扩展React.Component{
状态={
颜色:“红色”
}
getChildContext(){
返回{
颜色:this.state.color
};
}
componentDidMount(){
setTimeout(()=>this.setState({color:'blue'}),2000)
}
render(){
返回(
测试点击
);
}
}
Parent.childContextTypes={
颜色:React.PropTypes.string
}
类按钮扩展了React.Component{
render(){
返回(
{this.props.children}
);
}
}
Button.contextTypes={
颜色:React.PropTypes.string
};

我仍然无法让它对我有用,但由于你的答案显然是正确的,我将把它标记为答案谢谢,希望你能成功