反应tsx类创建useContexthook和如何在类中使用(附代码)

54 阅读1分钟

我试图用类组件来学习TSX,我知道它很老了,但我想弄清楚它是如何用类来工作的。

但它对这个类扩展组件来说相当具有挑战性

下面是我的第一个问题

func version:



const NavbarProvider = ({children}) =>{

const values ={
}

return(

<AuthContext.Provider    value={values} >{children}</AuthContext.Provider>

)
}

const useAuth = () =>useContext(AuthContext)

export {NavbarProvider,useAuth}

我想把这个版本放在类组件中,所以我做了类版本:

 
  const NavbarContext = createContext<any|null>(null)
  
  export class NavbarContextProvider extends Component<any,any>  { 
 
  setBag = (item:number) =>{
    this.setState(()=>({bag:item}))
  
  }

  value: any

  constructor(props:any) {
    super(props)

  this.state={
    bag:0
    
  }

  this.value={
    bag:this.state.bag,
    setBag:this.setBag
    }
    
      
}
 
 render() { 
 return ( <NavbarContext.Provider value={this.value}>{this.props.children} //there
 </NavbarContext.Provider> ) 

}
} 
export const useNavbarContext = useContext(NavbarContext)

 export default NavbarContextProvider

我的第一个问题是关于props.children的,我的逻辑说它需要像这样:


  constructor(props:any) {
    super(props)

this.props =props
}


 render() { 
 return ( <NavbarContext.Provider value={this.value}>{this.props.children} //there
 </NavbarContext.Provider> ) 

}

但是当我这样写的时候,在TSX中出现了只读道具的错误。所以如果没有构造函数,在渲染方法中使用props.children是如何发生的?

第二个问题,当我在主文件中调用useNavbarContext钩子时

  export class Navbar extends Component {
     items: any; 
     BagIndex: any;

constructor(props: {} | Readonly<{}>){
super(props)

this.BagIndex = useNavbarContext() // this part


 render() { 

 return ( 

  <div>
    <Menubar
  model={this.items} // I clear item for you read clear cod

  className={moduleCSS.Navbar}

 start={``}
  end={``}
/> 

</div> ) 
}} 


它给了我

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

我在里面写构造函数。我想这是类的主体。

我需要关于反应类组件与TSX视频的建议。 我不能很好地理解它的工作原理,我愿意接受新的信息来源......