简体   繁体   中英

React stateless functional component to class Component

Can you help me in changing this React stateless functional component to React class based component including the withRouter and history object as given?

const Menu = withRouter(({history}) => (
   <AppBar>

   </AppBar>
))
export default Menu

First, create your class component and then, create a constructor for the class. You can then define the states required inside the constructor, something like this-

export default class Menu extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
   SomeVar: xyz,
   AnotherVar: undefined
  }
 }

 render() {
  return withRouter(({history}) => (
   <AppBar> </AppBar>
  ));
 }
}
class Menu extends React.Component {
  render() {
    // you can use this.props.history anywhere in the class
    const { history } = this.props;
    return <AppBar>...</AppBar>
  }
}

export default withRouter(Menu);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM