How can I convert popover MATERIAL-UI functional component to class based component?

后端 未结 2 774
一个人的身影
一个人的身影 2021-01-06 11:11

I\'m trying to convert this functional component to class based component. I have tried for several hours but could not find where to place these const variable

2条回答
  •  无人及你
    2021-01-06 12:12

    First thing one need to understand is, how class based and functional components work. Also, when and where you use it.

    In short, I can say functional components are Used for presenting static data. And class based are Used for dynamic source of data.

    Here are few links for your reference.

    Class based component vs Functional components what is the difference ( Reactjs ) and React functional components vs classical components

    To answer your specific question.

    import React, { Component } from 'react';
    import { withStyles, makeStyles } from '@material-ui/styles';
    
    const useStyles = makeStyles(theme => ({
          typography: {
            padding: theme.spacing(2),
          },
    }));
    
    class SimplePopper extends Component {
       constructor(props){
          super(props)
          this.state = { anchorEl: null, setAnchorEl: null }; <--- Here see the state creation
          this.handleClick= this.handleClick.bind(this);
        }
    
       handleClick(event) {
            const { anchorEl, setAnchorEl } = this.state; <--- Here accessing the state
            setAnchorEl(anchorEl ? null : event.currentTarget);
       }
    
       render() {
          const { anchorEl, setAnchorEl } = this.state; <--- Here accessing the state
          const open = Boolean(anchorEl);
          const id = open ? 'simple-popper' : null;
          const { classes } = this.props;
    
          return (
            
    ............Rest of the JSX............
    ); } } export default withStyles(useStyles)(SimplePopper);

    Note that here I've used withStyles to wrap the style to your component. So, that the styles will be available as classNames.

    Explore the difference and convert the rest

    This is more enough to begin with.

提交回复
热议问题