最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Function components do not support contextType - Stack Overflow

programmeradmin1浏览0评论

Function ponents do not support contextType.

I encountered an issue when trying to add context to a React ponent that was wrapped with a React Router withRouter(...) function.

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)

Function ponents do not support contextType.

I encountered an issue when trying to add context to a React ponent that was wrapped with a React Router withRouter(...) function.

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)
Share Improve this question edited Jan 31, 2019 at 21:32 Tom Hofman asked Jan 31, 2019 at 17:48 Tom HofmanTom Hofman 5205 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

The solution to this issue is simply switch the last two lines like so:

export default withRouter(Toolbar)
Toolbar.contextType = UserContext
发布评论

评论列表(0)

  1. 暂无评论