功能组件不支持contextType

时间:2019-01-31 17:48:17

标签: javascript reactjs react-router react-router-dom

  

功能组件不支持contextType。

在尝试向使用React Router withRouter(...)函数包装的React组件添加上下文时遇到了一个问题。

import React, { Component } from 'react'
import UserContext from './UserContext'
class Toolbar extends Component {
  render(){
    return (
      <div>username: this.context.username</div>
    )
  }
}
Toolbar.contextType = UserContext
export default withRouter(Toolbar)

1 个答案:

答案 0 :(得分:0)

此问题的解决方案是像下面这样简单地切换最后两行:

export default withRouter(Toolbar)
Toolbar.contextType = UserContext