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

时间:2016-05-31 23:18:04

标签: reactjs redux

我希望添加完成的检查(一旦组件安装在CDM中)以检测userAgent - 用于移动/ flash / touchDevice检测到上下文而不是状态。这可能吗?如果是这样你会怎么做?当我尝试访问undefined的上下文值时,我正在获得isFlashInstalled。以下是设置上下文的组件的一瞥:

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 个答案:

答案 0 :(得分: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